JavaScript Object-Oriented Programming (11) Other inheritance methods, javascript object-oriented
1. Use the parent object as the prototype of the new object
Function object (o) {var n; function F () {} F. prototype = o; n = new F (); n. uber = o; return n;} var shape = {name: 'shape', toString: function () {if (this. uber) return this. uber. toString () + ',' + this. name; elsereturn this. name ;}} var twoDShape = object (shape); twoDShape. name = "2 D Shape"; alert (twoDShape. toString ());
2. In the Sub-constructor, call the Parent constructor Parent. apply (); and pass the parameter. In this way, the attributes bound to this of the Parent object become attributes of the sub-object at the same time.
Function Shape (id) {this. id = id;} Shape. prototype. name = 'shape'; shape. prototype. toString = function () {return this. name ;}; function Triangle () {Shape. apply (this, arguments); // native property inheritance}