1. JS is actually a non-object-oriented language, through the object's depth of copy to complete the inheritance
2. Inheritance Methods
There are two ways to inherit
1) prototype prototype mode
As an example,
varAnimal =function () { This. Type = ' Animal '; This. tmp = {name: ' hehe '}; This. Eat =function(TMP) {Console.log (' Animal eat '); }; This. modifytmp =function(TMP) { This. Tmp.name =tmp; }}varCat =function(name) { This. Type = ' Cat '; This. Name =name; This. Eat =function() {Console.log (' Cat eat: ' + This. Name); }}cat.prototype=NewAnimal ();varCAT1 =NewCat (' CAT1 '); Cat1.eat (); Cat1.modifytmp (' Lala '); Console.log (cat1.tmp); //Output LalavarCAT2 =NewCat (' Cat2 '); Cat2.eat (); Console.log (cat2.tmp); //Output LalaView Code
Note: There are pits here!!
Why is the output of Lala inherited from the prototype?
Because the type of TMP at this time is an object or an array, when prototype inheritance is performed, the inheritance is actually done through the object reference, at which point Cat1 Cat2 is pointing to the same animal object. If the TMP is the underlying type (string,int), there is no reference, so there is no need to worry.
TMP can be redefined to an external CAT1 Cat2 object for re-copying, which will point to two different objects, as shown in the following example:
varAnimal =function () { This. Type = ' Animal '; This. tmp = {name: ' hehe '}; This. Eat =function(TMP) {Console.log (' Animal eat '); }; This. modifytmp =function(TMP) { This. Tmp.name =tmp; return This. tmp; }}varCat =function(name) { This. Type = ' Cat '; This. Name =name; This. tmp = {}; This. Eat =function() {Console.log (' Cat eat: ' + This. Name); This. tmp = This. tmp; }}cat.prototype=NewAnimal ();varCAT1 =NewCat (' CAT1 '); Cat1.eat (); Cat1.tmp= cat1.modifytmp (' Lala '); Console.log (' CAT1 ', CAT1);//LalavarCAT2 =NewCat (' Cat2 '); Cat2.eat (); Cat2.tmp= Cat2.modifytmp (' Miaomiao '); Console.log (' Cat2: ', CAT2);//MiaomiaoConsole.log (' cat1 ', CAT1);//LalaView Code
2) Call apply method
This is the use of this object bogus.
"JavaScript" inheritance