Javascript 原型和对象属性。为什么他们的行为不同?
为什么原型与普通对象不同Javascript 原型和对象属性。为什么他们的行为不同?,javascript,object,prototype,Javascript,Object,Prototype,为什么原型与普通对象不同 var obj={'length':4} obj._length=obj.length console.log(obj._length); // 4 数组是一个对象,它的原型也是,所以应该看到相同的行为 var a=[0,1,2,3]; Array.prototype._length=Array.prototype.length; console.log(a.length,a._length); // 4,0 我不打算在实践中使用它,但是,我确
var obj={'length':4}
obj._length=obj.length
console.log(obj._length); // 4
数组是一个对象,它的原型也是,所以应该看到相同的行为
var a=[0,1,2,3];
Array.prototype._length=Array.prototype.length;
console.log(a.length,a._length); // 4,0
我不打算在实践中使用它,但是,我确实想更好地理解这里发生了什么
编辑:您如何看待相同的行为?在第一种情况下,您将在对象上创建一个名为“长度”的新属性,并在其中指定长度属性的值。因此,改变一个不会影响另一个。你可以这样确认
var obj={'length':4}
obj._length=obj.length
console.log(obj._length);
# 4
obj.length = 15;
console.log(obj._length);
# 4
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
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
在第二种情况下,创建数组对象时,将在对象本身上设置长度属性,而_length在原型链中,而不是在对象本身上
console.log(a.hasOwnProperty("length"), a.hasOwnProperty("_length"));
# true false
此外,您还在数组的原型中创建了一个名为_length的变量,默认长度为0 console.logArray.prototype.length;。因此,所有后续数组也将具有该属性
var a = [0, 1, 2, 3];
Array.prototype._length = Array.prototype.length;
console.log([]._length);
# 0
所以,我们在这里讨论两种不同的性质。长度特定于所有数组对象,其中as_长度是所有数组对象的公共长度
你可以这样确认
var obj={'length':4}
obj._length=obj.length
console.log(obj._length);
# 4
obj.length = 15;
console.log(obj._length);
# 4
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
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
因为_length不在其自身上,所以当您尝试访问它们时,它们会查找prototype链以在Array.prototype中找到一个。所以,他们都在打印0
如果您想使用_length属性获取长度,可以在原型中定义它,如下所示
var obj={'length':4}
obj._length=obj.length
console.log(obj._length);
# 4
obj.length = 15;
console.log(obj._length);
# 4
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
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
其实没有什么区别。在第二个示例中,您的错误是假设Array.prototype.length===a.length,这不是caee。