gpt4 book ai didi

JavaScript。引用文献问题。遗产。范围

转载 作者:行者123 更新时间:2023-12-02 16:59:41 26 4
gpt4 key购买 nike

看看我的问题:

我有一个如下所示的类:

var els=[];
var base = function(){
this.config = {}
}


var X1 = function(){
}
X1.prototype = new base();
X1.prototype.indexme = function(i){
this.config.index = i;
}
X1.prototype.add = function(){
var i = els.push(this)
this.indexme(i)
}

var teste = new X1();
teste.add();
var teste2 = new X1();
teste2.add();
var teste3 = new X1();
teste3.add();

console.log(els)

为什么 this.config.index 会被其他实例覆盖?

我预计 teste 的 config.index = 1; teste2 config.index=2 和 teste3 config.index=3

谢谢

最佳答案

X1 的所有实例共享相同的原型(prototype),即具有 config 属性的 base 实例。因此,X1 的所有实例共享相同的 config 属性。您可以将 this.config = {}; 行移至 X1 构造函数,也可以在 中定义 init() 函数base 为每个对象分配 this.config 并从 X1 构造函数调用 init()

关于JavaScript。引用文献问题。遗产。范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25859436/

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