我是 javascript 原型(prototype)继承的 Nerd 。我能理解下面代码中发生的事情
function Hamster() { }
Hamster.prototype = {
food: [],
found: function(something) {
this.food.push(something)
}
}
// Create two speedy and lazy hamsters, then feed the first one
speedy = new Hamster()
lazy = new Hamster()
speedy.found("apple")
speedy.found("orange")
alert(speedy.food.length) // 2
下面的行也是警告 2
因为这两个对象正在共享 Hamster
原型(prototype)的 food
数组
alert(lazy.food.length) // 2
但是如果我将数组的数据类型更改为数字,food
键不会在两个实例之间共享
function Hamster() { }
Hamster.prototype = {
food: 0,
found: function(something) {
this.food = something
}
}
// Create two speedy and lazy hamsters, then feed the first one
speedy = new Hamster()
lazy = new Hamster()
speedy.found(123)
alert(speedy.food) // 123
但是下面一行警告 0
,你能告诉我为什么这不警告 123
alert(lazy.food) // 0
最佳答案
Hamster
的每个实例都有自己的food
属性。但在第一个版本中,它们都指向同一个数组,您可以使用 push
对其进行修改。在第二个版本中,它们指向整数,不能就地修改; found
函数重新分配该实例的属性,这对其他实例没有影响。
要为每个实例赋予其自己的 food
数组属性,您需要使用分配它的构造函数。
你可以看到与下面类似的行为,它只使用普通变量而不是对象和继承。
arr1 = [];
arr2 = arr1;
arr1.push(1);
console.log(arr2); // prints [1]
int1 = 0;
int2 = int1;
int1 = 1;
console.log(int2); // prints 0
赋值运算符 '=' 从变量中删除指针
arr1 = [];
arr2 = arr1;
arr2 = ['Appple'];
console.log(arr1); // prints []
关于javascript - Javascript 原型(prototype)继承中数组和数字数据类型之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23065542/