One, the inheritance of the constructor
Steps for a constructor to inherit another constructor
1. Call the constructor of the parent class in the constructor of the
child class 2. Let the prototype of the child class point to the prototype of the parent class.
Code example
This example is that n inherits the constructor m after a is Instantiate an object n, then a has the attributes of both m and n.
The second way of writing
Key code:
//第一种方法:
function n(){
m.call(this) //继承m构造函数
this.color="red"
}
//第二种方法:
function n(){
this.base=m; //继承m构造函数的属性
this.base() //继承m构造函数的属性
this.color="red"
}
n.prototype = Object.create(m.prototype);
n.prototype.constructor=m
var a=new n()
The above two methods are all subclasses completely inherit the parent class, sometimes only a single method inheritance is needed
so that n only inherits the print method of m, and does not inherit other attributes of m. A
single method inherits the key code:
n.prototype.print=function(){
m.prototype.print.call(this)
}
Two, multiple inheritance
JavaScript does not provide the function of multiple inheritance, but it can be achieved through alternative methods. The specific steps are the
first step, the constructor C calls the parent class constructor A, and the parent class constructor B. The
second part, the prototype inheritance structure of the constructor C The prototype of function A. The
third part, the inheritance chain of constructor C plus the inheritance chain of constructor B. The
fourth part, constructor C specifies that the constructor is C itself.
Code example
3. Module encapsulation
1. Basic implementation method (will be exposed Module member, and the internal attribute state can be changed externally)
2. Encapsulate private variables: the way of constructing function
-
Method 1 (violating the principle of separating the constructor from the instance object, and is very memory intensive)
-
Method two (it looks natural, but its private variables can be read and written from outside)
Method three, encapsulate private variables: execute function writing
immediately, execute function writing immediately, and encapsulate related attributes and methods in a scope to achieve non-exposure Purpose of private members
4. Module enlargement mode
If a module is very large and needs to be divided into multiple modules or one module needs to inherit another module, this mode needs to be adopted at this time
var module1 = (function (mod){
mod.m3 = function () {
//...
};
return mod;
})(module1);