首页 > 代码库 > JavaScript Patterns 6.4 Prototypal Inheritance
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 fromvar parent = { name: "Papa"};// the new objectvar child = Object(parent);// testingalert(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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。