【问题标题】:Does this example represent "Prototypal Inheritance"?这个例子是否代表“原型继承”?
【发布时间】:2018-03-14 11:09:11
【问题描述】:

我有一个对象字面量 (a),稍后我用它来使另一个对象 (b) 添加一些属性,并再次借助 (b) 生成一个对象,即 (c) 并为其添加一些属性.

最后,我尝试访问 c.name,哪个浏览器首先在 c 中搜索,然后是 b,最后从对象 a 获取它(第二个警报相同)。但是,如果这个例子正确地代表“原型继承”,我有点困惑! (因为,不涉及具有原型属性的函数构造)。

var a = {name: "Jenny", age: 27}; 
var b = Object.create(a); 
b.state = "New York"; 
var c = Object.create(b); 
c.flag = "50 star flag"; 
alert(c.name); 
alert(b.age); 

【问题讨论】:

    标签: javascript html inheritance prototype


    【解决方案1】:

    是的,你创建的原型链是c -> b -> a

    var a = {};
    var b = Object.create(a);
    
    console.log(Object.getPrototypeOf(b) === a); // true
    
    var c = Object.create(b);
    
    console.log(Object.getPrototypeOf(c) === b); // true

    如果您对本示例中缺少构造函数感到困惑,请记住 Object.create 只是

    function Object.create(proto) {
        function F() {}
        F.prototype = proto;
        return new F();
    }
    

    所以new 和构造函数仍然在后台执行。有关Object.create 背后的基本原理,请参阅此classic article

    【讨论】:

      猜你喜欢
      • 2021-09-04
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      相关资源
      最近更新 更多