JavaScript Prototypal Inheritance:为什么调用child的getter / setter会影响parent?

时间:2014-01-21 18:50:50

标签: javascript inheritance prototypal

请参阅下面的小提琴/代码: http://jsfiddle.net/kmiklas/3YdTA/4/

问题:

  • 为什么调用子项的setter函数 - 在示例中,调用Object.create(99) - 更改父项的设置?请注意,虽然我们在橙色的上下文中调用了此函数,但它也会更改红色的值。
  • 更重要的是,如何将继承的getter / setter函数应用于子节点而不是父节点?
  • 我在这里缺少什么?

var Square = function () {
    var side;
    this.setSide = function(s) {
        side = s
    }
    this.getSide = function() {
        return side;
    }
}
var red = new Square();
var orange = Object.create(red);
red.setSide(100);
var $container = $('#container');
$container.append('orange.getSide(): ' + orange.getSide() + '<br>');
$container.append('red.getSide(): ' + red.getSide() + '</br><br>');
$container.append('<i>Now we call orange.setSide(99)...</i><br></br>');
orange.setSide(99);
$container.append('orange.getSide(): ' + orange.getSide() + ' <i>...as expected.<br></i>');
$container.append('red.getSide(): ' + red.getSide() + '!? <i>Why does the call to orange.setSide(99) affect the side length of the parent?</i></br>');

1 个答案:

答案 0 :(得分:2)

The Object.create() method creates a new object with the specified prototype object and properties.

MDN

 var orange = Object.create(red);

你是不是克隆的对象这样,你要创建一个新的裁判,所以你疯了原始对象的任何更改将影响所有的拷贝到这个对象

var x = {name:"foo",phone:"bar"};
var y = Object.create(x);

x.u = "123";

console.log(y);//{name: "foo", phone: "bar", u: "123"} 
console.log(x);//{name: "foo", phone: "bar", u: "123"} 

对象由Ref在javaScript中复制

DEMO

How do I correctly clone a JavaScript object?

上查看