请参阅下面的小提琴/代码: http://jsfiddle.net/kmiklas/3YdTA/4/
问题:
Object.create(99)
- 更改父项的设置?请注意,虽然我们在橙色的上下文中调用了此函数,但它也会更改红色的值。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>');
答案 0 :(得分:2)
The Object.create() method creates a new object with the specified prototype object and properties.
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中复制