gpt4 book ai didi

javascript - 关于 JavaScript 原型(prototype)

转载 作者:行者123 更新时间:2023-11-28 06:45:12 26 4
gpt4 key购买 nike

关于 javascript 原型(prototype)的一个奇怪问题:

(function(w){
if(!w)
return;

var TestJS = function(){
};

TestJS.prototype = {

data:{},
initData:function(){
this.data={
val_name_1 : 1,
val_name_2 : 2,
val_name_3 : "hello-3"
};
console.log(this.data);
return this;
},

TestChildJS:{
initChild:function(){
console.log(TestJS);
console.log(TestJS.data);
console.log(new TestJS().data.val_name_1);
console.log(TestJS.data.val_name_1);
}
}
};
window.TestJS = new TestJS();
})(window);

为什么“TestChildJS”无法获取“val_name_1”?

TestJS.initData();
console.log(TestJS.TestChildJS.initChild());

console pic

所以我必须这样编写代码:

(function(w){
if(!w)
return;

var TestJS = function(){
};
TestJS.prototype = {

data:{},

initData:function(){
this.data={
val_name_1 : 1,
val_name_2 : 2,
val_name_3 : "hello-3"
};
console.log(this.data);
this.TestChildJS.initParentData(this);
return this;
},

TestChildJS:{
parentData:{},

initParentData:function(parent){
this.parentData = parent.data;
return this;
},

initChild:function(){
console.log(this.parentData);
}
}
};

window.TestJS = new TestJS();
})(window);

如何使用第一种方式获取第二种方式的内容?

最佳答案

why 'TestChildJS' can not get 'val_name_1'?

何时:

TestJS.initData();

运行后,它会向 TestJS 对象添加一个 data 属性(由 window.TestJS = new TestJS() 分配的属性) 。该属性不会被任何其他对象继承。

时间:

console.log(new TestJS().data.val_name_1);

运行后,new TestJS() 返回的对象尚未调用其 initData 方法,因此它没有数据 em> 属性,并且它不会从构造函数继承它(因为该属性直接位于构造函数本身,而不是其原型(prototype)上)。

另请注意,将新对象分配给 this.data 会直接在实例上创建一个属性,因此添加到 this.data 会修改实例的数据 对象,而不是构造函数原型(prototype)上的对象。

代码中的模式(尤其是第二个)似乎不必要地复杂。

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

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