在学习angularjs时,我发现如果你把对象放在一个原型对象中,从原型继承的实例会在赋值时改变原型的对象。
示例:
function Person(name) {this.name = name;}
Person.prototype = {species : "homo-sapiens" , characteristics : { "legs" : 2 , "height" : 175}}
var joe = new Person("joe");
joe.characteristics.legs = 1 ;
console.log(Person.prototype.characteristics) //Object {legs: 1, height: 175}我所展示的是原型的实例(joe)改变了原型本身上的对象的值,因为它继承了一个对象(特征),而不是一个原语。
我的问题如下:原型在大多数情况下是用来保存原语的吗?(在大多数情况下,您永远不会希望实例更改原型的值。Angular.js实际上是这样做的,但在极少数情况下,您实际上需要一个子实例来写入原型)。如果你真的想把一个对象放在原型上,而没有实例在赋值时写入原型,你会怎么做呢?
发布于 2013-12-01 17:47:47
这实际上与prototype无关,只是一般的JS行为。
解决方案是在构造函数中从原型复制对象,
function Person() {
this.characteristics = angular.copy(this.characteristics);
}
Person.prototype = { whatever };以上假设angular可用于angular.copy函数。否则,您将需要通过迭代属性并复制到新的属性中来手动复制对象。
发布于 2013-12-01 18:13:21
要获得您期望的行为,请尝试以下操作:
function Person(name) {
this.name = name;
this.species = "homo-sapiens";
this.characteristics = { "legs" : 2 , "height" : 175};
}
// NOTE: line below is no longer needed, but I'm keeping it
// here just so you can see its output for comparison below
Person.prototype = {species : "homo-sapiens",
characteristics : { "legs" : 2 , "height" : 175}}
var joe = new Person("joe");
joe.species = "regular old joe";
console.log('Person.prototype.species:', Person.prototype.species);
// Line above prints: Person.prototype.species: homo-sapiens
console.log('joe.species:', joe.species);
//joe.species: regular old joe
joe.characteristics.legs = 1 ;
console.log('Person.prototype.characteristics:', Person.prototype.characteristics);
//Person.prototype.characteristics: Object {legs: 2, height: 175}
console.log('joe.characteristics:', joe.characteristics);
//joe.characteristics: Object {legs: 1, height: 175} 澄清一下,你的问题真的与angular无关,它只与javascript基于继承的原型以及它是如何工作的有关。
https://stackoverflow.com/questions/20310809
复制相似问题