Prototype javascript原型不工作
我是不是搞错了原型应该做什么了,还是这根本不起作用Prototype javascript原型不工作,prototype,javascript,function-prototypes,Prototype,Javascript,Function Prototypes,我是不是搞错了原型应该做什么了,还是这根本不起作用 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.
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();
我想我要问的是,使用下面代码的正确方法是什么
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分配给wrap console.log,因为console显然不是一个标准对象。因此,它不是应用方法的标准函数对象。我确实使用谷歌的证明。是的,正确的版本如下。转储程序是一个构造函数。因此,它初始化列表成员 下面,我们使用所需的方法设置转储程序原型。这些也可以使用这个。任何转储程序实例(如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();
是的,正确的版本如下所示。转储程序是一个构造函数。因此,它初始化列表成员 下面,我们使用所需的方法设置转储程序原型。这些也可以使用这个。任何转储程序实例(如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();
没有办法实际使用d作为转储函数?@andrewjackson,如果您将dump设置为单例的话。但这破坏了使用原型的全部意义。除非有必要,否则不要试图反对JavaScript对象模型。我不想成为一个痛苦的人,但是你有没有一个例子来说明单例是什么样子的,这将使这成为可能?只是为了提供信息……没有办法实际使用d作为转储函数?@andrewjackson,如果您将dump设置为单例的话。但这破坏了使用原型的全部意义。除非有必要,否则不要试图反对JavaScript对象模型。我不想成为一个痛苦的人,但是你有没有一个例子来说明单例是什么样子的,这将使这成为可能?仅供参考。。。