gpt4 book ai didi

javascript - "this"在另一个对象的数组内访问 's "this"- javascript

转载 作者:行者123 更新时间:2023-11-28 17:35:36 25 4
gpt4 key购买 nike

考虑这个例子:

如果你要运行上面的代码,控制台消息将是100。为什么当我将100添加到obj2的“this”中的位置时,它打印出100?如何使 obj2 拥有自己独特的“this”?另请注意,这是我的代码的简化示例,我不能只在 obj2 中创建一个包含所有内容的单独对象。

var obj1 = function() {
this.obj2Arr = [];
this.pos = {
"x": 0,
"y": 0
};
this.obj2Arr.push(new obj2(this.pos));
console.log(this.pos.x);
// Prints out 100 even though obj2 was where I added the 100 for it's "this".
// Why does it do that, and how do I make obj2's "this" unique to it?
};

var obj2 = function(pos) {
this.pos = pos;
this.pos.x = this.pos.x + 100;
};

var example = new obj1();
console.log(example);

最佳答案

这是因为 pos 是一个对象,并且对象在 JavaScript 中始终通过引用传递。

要回答您的问题:使用Object.assign 创建一个新对象:

var obj1 = function() {
this.obj2Arr = [];
this.pos = {
"x": 0,
"y": 0
};
this.obj2Arr.push(new obj2(Object.assign({}, this.pos)));
console.log(this.pos.x);
};

var obj2 = function(pos) {
this.pos = pos;
this.pos.x = this.pos.x + 100;
};

var example = new obj1();
console.log(example);

关于javascript - "this"在另一个对象的数组内访问 's "this"- javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49212161/

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