There is a basic pattern for implementing the prototype chain, which is roughly the following code: function A () { this.property = true;} A.prototype.getavalue = function () { return this.property; };function B () { This.property = false;} inherited the Ab.prototype = new A (); B.prototype.getbvalue = function () { return This.property;}; var instance = new B (); Console.log (Instance.getbvalue ());//true; borrowing constructor function A () { this.color = ["Red", "Blue"];} function B () { //inherited a a.call (this);} var Instance1 = new B (); Instance1.color.push ("yellow"); Console.log (Instance1.color);//red,blue,yellow; var instance2 = new B (); Console.log (Instance2.color);//red,blue; 1, there is a great advantage to borrowing constructors in relation to the prototype chain, You can pass parameters to a superclass constructor in a subtype constructor, as follows: function A () { this.name = name;} function B () { //inherits a, passing parameters a.call (this, "Hello"); // Instance Properties; this.age = 27;} var instance = new B (); Console.log (instance.name);//helloconsole.log (instance.age);//272. The question of borrowing constructors: if you simply borrow a constructor, you will not be able to avoid the problem with the constructor pattern, which is defined in the constructor, so the reuse of the function cannot be discussed. Moreover, the methods defined in the super-type prototype are not visible to the subtypes, resulting in the fact that all types can only use the constructor pattern. Three. Combination inheritance, sometimes referred to as classic inheritance, refers to the prototype chain and borrowed the technology of the constructor into a piece, so as to play both the length of an inheritance model, the idea is: using the prototype chain to achieve the inheritance of the prototype properties and methods, and by borrowing the constructor to implement the inheritance of the instance properties. function A (name) { this.name = name; this.colors = ["Red", "Blue"];} A.prototype.sayname = function () { alert (this.name);}; function B (name,age) { a.call (this,name); this.age = age;} Inheritance method B.prototype = new A (); B.prototype.constructor = B; B.prototype.sayage = function () { alert (this.age);}; var Instance1 = new B ("hehe"), Instance1.colors.push ("yellow"); Instance1.sayname ();//heheinstance1.sayage ();//27 ; var Instance2 = new B ("haha"); Console.log (instance2.colors);//red,blueinstance1.sayname ();// Hahainstance1.sayage ();//28;
Inheritance in
JS