Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newbie: Need some explanation on this js code

Tags:

javascript

I am learning javascript, and I have read somewhere the following code:

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
newObject = Object.create(oldObject);

I understand that the Object.create function return a new object which inherited the object 'o' that has been passed as a parameter to the Object.create function. But, I don't understand what is the sense to make this? I mean, even the Object.create function returned a new object, but the new object and the old object has no difference. Even new object inherit old one, there are no new methods defined in the new object. So, in what situation do we need the above code to get the new object??

like image 995
Mellon Avatar asked Oct 11 '22 10:10

Mellon


1 Answers

Several other answers are already doing the job of explaining this, but I'd like to add an example:

var steve = { eyes: blue, length: 180, weight: 65 };
var stevesClone = Object.create(steve);

// This prints "eyes blue, length 180, weight 65"
for (var property in stevesClone) {
  console.log(property, stevesClone[property]);
}

// We can change stevesClone without changing steve:
stevesClone.eyes = "green";
stevesClone.girlfriend = "amy";


// This prints "eyes green, length 180, weight 65, girlfriend amy"
for (var property in stevesClone) {
  console.log(property, stevesClone[property]);
}

// But if we alter steve, those properties will affect stevesClone as well
// unless they have also been assigned to stevesClone directly:
steve.father = "carl";
steve.eyes = "red";

// So, the clone got steves father carl through inheritance, but keeps his
// green eyes since those were assigned directly to him.

// This prints "eyes green, length 180, weight 65, girlfriend amy, father carl"
for (var property in stevesClone) {
  console.log(property, stevesClone[property]);
}

Object.create creates a new object, from an existing one, and uses the prototype chain to maintain a relationship between them. Anything asked from stevesClone will propagate up to steve if the clone does not have those properties himself. Therefore, changes to steve might affect the clone, but never vice versa.

like image 113
Jakob Avatar answered Oct 19 '22 03:10

Jakob