gpt4 book ai didi

javascript - 原型(prototype)和对象属性。为什么他们的行为不同?

转载 作者:行者123 更新时间:2023-11-30 12:35:32 26 4
gpt4 key购买 nike

为什么原型(prototype)与普通对象不同?

var obj={'length':4}

obj._length=obj.length

console.log(obj._length); // 4

数组是一个对象,它的原型(prototype)也是,所以应该看到相同的行为......

var a=[0,1,2,3];


Array.prototype._length=Array.prototype.length;


console.log(a.length,a._length); // 4,0

我不打算在实践中使用它,但我确实想更好地理解这里发生的事情。

编辑:您如何看待相同的行为?

最佳答案

在第一种情况下,您要在对象上创建一个名为 _length 的新属性,并在其中分配 length 属性的值。所以,改变一个不会影响另一个。你可以这样确认

var obj={'length':4}
obj._length=obj.length
console.log(obj._length);
# 4
obj.length = 15;
console.log(obj._length);
# 4

在第二种情况下,当您创建一个 Array 对象时,length 属性将设置在对象本身上,而 _length 位于原型(prototype)链中,而不是在对象本身上。

console.log(a.hasOwnProperty("length"), a.hasOwnProperty("_length"));
# true false

此外,您还在 Array 的原型(prototype)中创建了一个名为 _length 的变量,默认长度为 0(console.log(Array.prototype.length);).因此,所有后续数组也将具有该属性。

var a = [0, 1, 2, 3];
Array.prototype._length = Array.prototype.length;
console.log([]._length);
# 0

因此,我们在这里讨论的是两种不同的属性。 length 特定于所有 Array 对象,而 _length 对所有 Array 对象都是通用的。

你可以这样确认

var a = [0, 1, 2, 3];
Array.prototype._length = Array.prototype.length;
console.log([1, 2, 3]._length);
# 0
console.log([1, 2, 3, 4]._length);
# 0

由于 _length 不在它们自己上,当您尝试访问它们时,它们会查找原型(prototype)链以在 Array.prototype 中找到一个。所以,他们都在打印 0。

如果想通过_length属性获取length,可以在原型(prototype)中定义,像这样

Object.defineProperty(Array.prototype, "_length", {
get: function() {
return this.length;
},
set: function(newValue) {
this.length = newValue;
}
});

console.log([]._length);
# 0
console.log([1, 2, 3]._length);
# 3

关于javascript - 原型(prototype)和对象属性。为什么他们的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26193426/

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