简体   繁体   中英

Right way to use Prototypal Inheritance in JavaScript?

Using Crockford's method ( http://javascript.crockford.com/prototypal.html ) doesn't work when we have reference values in properties (an array in the supertype) as this is common among all the objects.

So, what's really the recommended way to do object inheritance in Javascript that doesn't have problem and that visually encapsulates better all the object's methods and properties?

Example:

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
var p1 = {name: "nick", friends : ["a1", "a2"]};
var p2 = Object.create(p1);
p2.name ="john";
p2.friends.push("andre");
alert(p1.friends);
alert(p2.friends);
alert(p1.name);
alert(p2.name);

The friends array returns the same values for both p1 and p2, while I expect that it returns different values.

Well, the members higher in the prototype chain are "shared", that's the goal of prototypal inheritance...

However, you can assign an own property to the newly created object (just like you do with the name property, for example:

var foo = {foo: "xxx", array : ["a1", "a2"]};

var bar = Object.create(foo);
bar.foo = "yyy";
bar.array = ["b1", "b2"];
bar.array.push("bar");

alert(foo.array);   // ["a1", "a2"]
alert(bar.array);    // ["b1, "b2", "bar"]
alert(foo.foo);     // "xxx"
alert(bar.foo);     // "yyy"

The standard Object.create method, available on the latest browser versions , provides a way to create own properties, using a second argument, for example you could:

// ...
var bar = Object.create(foo, {
  foo: { value: 'yyy'},
  array: {value: ["b1", "b2"] }
});
// ...

Can you provide an example of what doesn't work? Prototypal inheritance is really meant for object literals. If you are trying to modify something created as an array, the only way I know of using inheritance is modifying Array.prototype.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM