简体   繁体   English

如何使用原型继承?

[英]How to use prototypal inheritance?

I have an object that looks like this: 我有一个看起来像这样的对象:

var o = {
    prototype: {
        foo: function(){console.log('bar');}
    }
}

My understanding is that when I do Object.create(o) the returned object should have a method .foo . 我的理解是,当我执行Object.create(o) ,返回的对象应该具有方法.foo

However, what if I also attach a create method to o ? 但是,如果我也将create方法附加到o怎么办?

var o = {
    prototype: {
        foo: function(){console.log('bar');}
    },
    create: function(){}
}

Does the prototypal magic of javascript do something different in this case? 在这种情况下,JavaScript的原型魔术会有所不同吗?

Your understanding is incorrect. 您的理解不正确。 You would have to do something like this: 您将必须执行以下操作:

var o = {
    __proto__: {
        foo: function() {
            console.log('bar');
        }
    }
};

so that the object returned from Object.create(o) would have the foo method. 因此从Object.create(o)返回的对象将具有foo方法。

var o2 = Object.create(o);
o2.foo(); // prints bar

Modern browsers have implemented the __proto__ as a way of accessing the internal [[Prototype]] chain of an object. 现代浏览器已将__proto__实现为一种访问对象内部[[Prototype]]链的方式。 It is not actually in the standard and it's direct use is discouraged and may even lead to suboptimal code due to possible optimizations done by the browser on the __proto__ property. 它实际上不是标准的,并且不建议直接使用,甚至可能由于浏览器对__proto__属性进行的优化而导致代码不理想。

In the example above the __proto__ fakes the internal representation of the prototype chain to demonstrate that Object.create connects the internal [[Prototype]] , ie the __proto__ property. 在上面的示例中, __proto__伪造了原型链的内部表示,以证明Object.create连接了内部[[Prototype]] ,即__proto__属性。

The .prototype property which is on all function objects, for example: 所有功能对象上的.prototype属性,例如:

var o = function() {};
typeof o.prototype  // returns "object"

Is used by the new operator in order to populate the internal [[Prototype]] (ie the __proto__ property) and build that instances prototype chain. 由new运算符使用,以填充内部[[Prototype]] (即__proto__属性)并构建该实例的原型链。

If you did the following 如果您执行以下操作

var o = {
    __proto__: {
        foo: function() {
            console.log('bar');
        }
    }, 
    create: function() {},
};

o2 = Object.create(o);

o2 would have both methods except they would be on different levels of the prototype chain, something like: o2将同时具有这两种方法,但它们将位于原型链的不同级别,例如:

{ 
  __proto__: {
     create: function() { ... },
     __proto__: {
        foo: function() { ... }
     }
}

Prototype is just a property that points on constructor function. 原型只是指向构造函数的属性。 In JS, you can add properties dynamically on any objects. 在JS中,您可以在任何对象上动态添加属性。 If you want to add properties in a class (I mean all objects which is an instance of that class), you must add properties to its prototype. 如果要在类中添加属性(我的意思是作为该类实例的所有对象),则必须在其原型中添加属性。

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

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