JavaScript Patterns 6.4 Prototypal Inheritance
2014-07-18 23:42 小郝(Kaibo Hao) 阅读(323) 评论(0) 编辑 收藏 举报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)
作者:小郝
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。