【发布时间】:2012-02-18 06:19:08
【问题描述】:
我误会了 .prototype 应该做什么,还是这不起作用??
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();
我希望“test1”和“test2”通过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。
【问题讨论】:
标签: prototype javascript function-prototypes