简体   繁体   English

在JavaScript中使用原型继承的正确方法?

[英]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. 当我们在属性(超类型的数组)中具有引用值时,使用Crockford的方法( http://javascript.crockford.com/prototypal.html )不起作用,因为这在所有对象中都很常见。

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? 那么,在Javascript中没有问题并且在视觉上更好地封装对象的所有方法和属性的真正推荐方法是什么?

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. friends数组为p1和p2返回相同的值,而我希望它返回不同的值。

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: 但是,您可以将自己的属性分配给新创建的对象(就像使用name属性一样,例如:

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: 最新的浏览器版本上提供了标准的 Object.create方法,该方法提供了使用第二个参数创建自己的属性的方法,例如,您可以:

// ...
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. 如果您试图修改创建为数组的内容,那么我知道使用继承的唯一方法就是修改Array.prototype。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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