Question

Please see the fiddle/code below: http://jsfiddle.net/kmiklas/3YdTA/4/

Questions:

  • Why does a call to the setter function of a child--in the example, the call to Object.create(99)--change the setting of the parent? Note how, although we've invoked this function in the context of orange, it's also changing the value for red.
  • More importantly, how can inherited getter/setter functions be applied to the child, and not the parent?
  • What am I missing here?

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>');
Was it helpful?

Solution

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

MDN

 var orange = Object.create(red);

You are not cloning the object this way, you are creating a new ref to it so any changes you mad to the original object will affect the all the copies to this object

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"} 

object are copied by Ref in javaScript

DEMO

see this on How do I correctly clone a JavaScript object?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top