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。
+1你打我吧! – maerics 2012-02-18 06:30:20
有没有办法实际使用“d”作为转储功能? – Shea 2012-02-18 06:32:20
@andrewjackson,可能如果你使'dump'成为一个单身人士。但是这破坏了使用'prototype'的整个观点。除非必须,否则不要试图与JavaScript对象模型作斗争。 – 2012-02-18 06:36:08