码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript Patterns 6.4 Prototypal Inheritance

时间:2014-07-19 08:36:01      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   java   color   strong   

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

JavaScript Patterns 6.4 Prototypal Inheritance,布布扣,bubuko.com

JavaScript Patterns 6.4 Prototypal Inheritance

标签:des   style   blog   java   color   strong   

原文地址:http://www.cnblogs.com/haokaibo/p/Prototypal-Inheritance.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!