2012-02-18 29 views
1

我在误认为.prototype应该做什么,或者这只是不工作?javascript原型不起作用

window.dump = function() { 
    for (var i = 0, x = dump.list.length; i < x; ++i) console.log.apply(this, dump.list[i]); 
    if (arguments.length && typeof arguments[0] === 'boolean' && arguments[0]) dump.purge(); 
} 
dump.prototype = { 
    list : [], 
    log : function() { 
     dump.list.push(arguments); 
    }, 
    purge : function() { 
     dump.list = []; 
    } 
} 
dump.log('test1'); 
dump.log('test2'); 
dump(); 

我想到“测试1”和“测试2”通过console.log传递,而不是dump.log没有定义。但是dump.prototype.log是。

编辑:我试了下面,我似乎无法得到这个原型的东西正确。

window.dump = new function() { 
    this.list = []; 
    this.log = function() { 
     this.list.push(arguments); 
    } 
    this.purge = function() { 
     return this.list = []; 
    } 
    return function() { 
     for (var i = 0, x = this.list.length; i < x; ++i) console.log.apply(this, this.list[i]); 
     if (arguments.length && typeof arguments[0] === 'boolean' && arguments[0]) this.purge(); 
    } 
} 

我想我问的是什么是正确的方式能够使用我的代码如下?

dump.log('test1'); 
dump.log('test2'); 
dump(); 

编辑:这是最后的结果感谢Matthew Flaschen,感谢所有对此感兴趣的人。

(function() { 
    var console_log = Function.prototype.bind.call(console.log, console); 
    window.dump = function() { 
     for (var i = 0, x = dump.list.length; i < x; ++i) console_log.apply(this, dump.list[i]); 
     if (arguments.length && typeof arguments[0] === 'boolean' && arguments[0]) dump.purge(); 
    }; 
    dump.list = []; 
    dump.log = function() { 
     dump.list.push(arguments); 
    } 
    dump.purge = function() { 
     dump.list = []; 
    } 
})(); 

我已经指派console_log包裹console.log,因为很明显console是不是一个标准的对象。因此它不是apply方法的标准Function对象。证明我确实使用Google。

回答

6

是的,正确的版本将在下面。 dumper是一个构造函数。因此,它初始化list成员。

下面,我们设置dumper原型与所需的方法。这些也可以使用this。任何dumper(例如d)的实例都会有这些方法。

window.dumper = function() { 
    this.list = []; 
}; 

dumper.prototype = { 

    log : function() { 
     this.list.push(arguments); 
    }, 
    purge : function() { 
     this.list = []; 
    }, 
    dump : function() { 
     for (var i = 0, x = this.list.length; i < x; ++i) console.log.apply(this, this.list[i]); 
     if (arguments.length && typeof arguments[0] === 'boolean' && arguments[0]) this.purge(); 
    } 
} 


var d = new dumper();   

d.log('test1'); 
d.log('test2'); 
d.dump(); 
+0

+1你打我吧! – maerics 2012-02-18 06:30:20

+0

有没有办法实际使用“d”作为转储功能? – Shea 2012-02-18 06:32:20

+0

@andrewjackson,可能如果你使'dump'成为一个单身人士。但是这破坏了使用'prototype'的整个观点。除非必须,否则不要试图与JavaScript对象模型作斗争。 – 2012-02-18 06:36:08