JS is a very free language, there is no type of strong language restrictions, the implementation of a function is often a lot of practice. Inheritance is one of them, in the JS inheritance can be divided into four categories, the above an article also mentioned some, the following began to elaborate on the inheritance of JS .
1, the prototype inheritance --- the simplest, most commonly used
function Funca () { this. show=function() { console.log ("Hello");} } function FUNCB () {}funcb.prototype=new Funca (); var b=New FUNCB (); B.show ();
Here is the use of the characteristics of the prototype chain implementation, the disadvantage is also obvious, if the hierarchy of inheritance is more, the method of modifying the top-level prototype, will affect all of the following objects.
2, prototype posing:
functionFunca (age) { This. Name= "Xiaoxiao"; This. age=Age ; This. show=function() {Console.log ( This. name+ This. Age)}}functionFUNCB () { This. parent=Funca; This. Parent (40); Delete This. Parent;}varb=NewFUNCB (); B.show ();
This method of inheritance is very well understood, but the Funca in the code to get FUNCB to execute, in fact, can be interpreted as:
functionFunca (age) { This. Name= "Xiaoxiao"; This. age=Age ; This. show=function() {Console.log ( This. name+ This. Age)}}functionFUNCB () {//This.parent=funca; //this.parent (+); //Delete this.parent; //actually, the above process is not about moving Funca. This. Name= "Xiaoxiao"; This. age=Age ; This. show=function() {Console.log ( This. name+ This. Age)}}varb=NewFUNCB (); B.show ();
Do you understand?
3. Call and apply
This in the above article to also mentioned, also detailed explained the reason, I believe that if the prototype of the understanding of this so easy .
Here's not much to say, look at the code:
function Funca () { this . Show = function function FUNCB () { this . Read = function () {}} var a = new Funca (); var b = new FUNCB (); Funca.call (b); // use call a.show ("a" "B");
the call and apply effect is the same, but the method of communication is not the same, but the recommended call, because the efficiency of apply is much lower, as for why, the following will be said.
4. Copy Inheritance
functionFunca () { This. name= "Hello"; This. show=function() {Console.log ( This. Name); }}functionFUNCB () { This. extend=function(o) { for(varPincho) { This[p]=O[p]; } }}varA=NewFunca ();varb=NewFUNCB (); B.extend (a); B.show ();
This method of extend , similar to jquery , works by traversing the attributes in a to b .
Well, the above is today's content, relatively simple, as long as good at summing up, these believe in your study will help. This in the next write context .
Written in 2015.11.16
21st JS Four ways of inheriting