zoukankan      html  css  js  c++  java
  • JavaScript Patterns 6.4 Prototypal Inheritance

    No classes involved; Objects inherit from other objects.

    Use an empty temporary constructor function  F().  Set the prototype of  F() to be the parent object. Return a new instance of the temporary constructor.

    function Object(o) {
    
        function F() {}
    
        F.prototype = o;
    
        return new F();
    
    }
    
    // object to inherit from
    
    var parent = {
    
        name: "Papa"
    
    };
    
    // the new object
    
    var child = Object(parent);
    
    // testing
    
    alert(child.name); // "Papa"

      

    Addition to ECMAScript 5

    In ECMAScript 5, the prototypal inheritance pattern becomes officially a part of the language. This pattern is implemented through the method Object.create().

    var child = Object.create(parent);

    Object.create()accepts an additional parameter, an object. The properties of the extra object will be added as own properties of the new child object being returned.

    var child = Object.create(parent, {
    
        age: { value: 2 } // ECMA5 descriptor
    
    });
    
    child.hasOwnProperty("age"); // true

    References: 

    JavaScript Patterns - by Stoyan Stefanov (O`Reilly)

  • 相关阅读:
    Web API总结
    @Html.Raw() 方法输出带有html标签的字符串
    jQuery
    图与树基础-完全图的判定
    图和树基础-蒜头君旅行
    PAT乙级1008
    PAT乙级1007
    PAT乙级1005
    PAT乙级1001
    前端工程化-webpack简介(一)
  • 原文地址:https://www.cnblogs.com/haokaibo/p/Prototypal-Inheritance.html
Copyright © 2011-2022 走看看