Newbie: you need to clarify this js code

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

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

I understand that a function Object.createreturns a new object that inherited the o ' object , which was passed as a parameter to the function Object.create. But I do not understand what is the point of doing this? I mean that even the function Object.createreturned a new object, but the new object and the old object do not differ. Even a new object inherits the old one; there are no new methods in the new object. So, in what situation do we need the above code to get a new object?

+5
source share
4 answers

, :

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 . , stevesClone, steve, . steve , .

+3

"" JavaScript, -.

, newObject "" oldObject. oldObjects, . , newObject , oldObject.

, JavaScript .

+1

After running this code, you can:

newObject();

I have no idea why, since the function body is empty, you can run newObject();whatever you want for the effect.

The idea is that you turn the object into a function, making the resulting value (function) still available as an object (consider the prototype part).

0
source

It is used for inheritance. Check out this link: http://javascript.crockford.com/prototypal.html

0
source

All Articles