gpt4 book ai didi

prototype - JavaScript 原型(prototype)不工作

转载 作者:行者123 更新时间:2023-11-30 08:11:46 25 4
gpt4 key购买 nike

我是不是误会了 .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 是。

编辑:我已经尝试了以下方法,但我似乎无法正确处理这个原型(prototype)。

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。

最佳答案

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

下面,我们使用所需的方法设置 dumper 原型(prototype)。这些也可以使用thisdumper 的任何实例(例如 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();

关于prototype - JavaScript 原型(prototype)不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9339150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com