Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/402.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript。参考问题。遗产范围_Javascript - Fatal编程技术网

javascript。参考问题。遗产范围

javascript。参考问题。遗产范围,javascript,Javascript,看看我的问题: 我有一个类似这样的类: 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(thi

看看我的问题:

我有一个类似这样的类:

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)
为什么将此.config.index覆盖到其他实例

我希望teste的config.index=1;teste2 config.index=2和teste3 config.index=3


谢谢

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

什么是
this.teste(i)
?此外,您还继承了整个
config
对象。它总是同一个对象。你把X1对象推到els上,所以索引不会是一个数字。你们为什么要投反对票?我不认为这是一个天真的问题。This.config引用了X1.prototype.config,并且X1的所有实例将共享同一个原型,因此teste1、teste2和teste3将获得相同的结果,因为config.indexPrototype附加到类定义中,所以您可以将原型视为类的静态属性。显然,某个类的每个实例都将共享同一个原型。这里有一个更好的方法来设置继承:这个想法是,如果我在另一个类的init中复制this.config,那么它只是我的另一个类的一个模型,这是一个糟糕的解决方案?还有一个疑问。如果我这样做:this.config={index:var},我的所有实例都会得到正确的值。为什么此.config.index会获得相同的值?理论上,这个.config在原型中已经有引用了吗?或者简单地说,我对引用进行了属性清理?当您将
config
属性分配给
this
时,它会在原型中隐藏相同的属性,但原型属性仍然存在。