She*_*hea 1 javascript prototype function-prototypes
我错误.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();
Run Code Online (Sandbox Code Playgroud)
我希望传递"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();
}
}
Run Code Online (Sandbox Code Playgroud)
我想我要问的是,能够如下使用我的代码的正确方法是什么?
dump.log('test1');
dump.log('test2');
dump();
Run Code Online (Sandbox Code Playgroud)
编辑:感谢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 = [];
}
})();
Run Code Online (Sandbox Code Playgroud)
我必须分配console_log包装console.log,因为显然console不是标准对象.因此,它不是Function该apply方法的标准对象.证明我确实使用谷歌.
是的,正确的版本如下. 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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3648 次 |
| 最近记录: |