Summary of methods of inheritance in JS (apply,call,prototype)

Source: Internet
Author: User

One, JS in object inheritance

There are three ways of inheriting in JS

1.js Prototype (prototype) Implementation inheritance

The code is as follows:
<span style= "<span style=" font-size:18px ">"Text/javascript" >functionPerson (name,age) { This. name=name;  This. age=Age ; } Person.prototype.sayHello=function() {alert ("Use prototype to get Name:" + This. Name); }      varPer=NewPerson ("Ma Xiao", 21); Per.sayhello (); //output: Use prototype to get Name: Ma Xiao          functionStudent () {} Student.prototype=NewPerson ("Hongru", 21); varstu=NewStudent (); Student.prototype.grade=5; Student.prototype.intr=function() {alert ( This. grade); } Stu.sayhello ();//output: Use prototype to get name: HongruStu.intr ();//Output: 5</script> </body> 


2. Constructor implementation inheritance

The code is as follows:
<span style= "font-size:18px" >functionParent (name) { This. name=name;  This. sayparent=function() {alert ("Parent:" + This. Name); }      }      functionChild (name,age) { This. tempmethod=Parent;  This. Tempmethod (name);  This. age=Age ;  This. saychild=function() {alert ("Child:" + This. name+ "Age:" + This. Age); }      }      varParent=NewParent ("Jiang Jiansen"); Parent.sayparent (); //output: "Parent: Jiang Jiansen"    varChild=NewChild ("Li", 24);//output: "Child: Li age:24"Child.saychild (); </script> </body> 

3.call, apply implementation inheritance

The code is as follows:
<span style= "font-size:18px" >functionPerson (name,age,love) { This. name=name;  This. age=Age ;  This. love=Love ;  This. say=functionsay () {alert ("Name:" +name); }      }      //Call mode    functionStudent (name,age) {Person.call ( This, Name,age); }      //Apply Method    functionTeacher (name,love) {person.apply ( This, [Name,love]); //person.apply (this,arguments);//With the same effect as the previous sentence, arguments}

The similarities and differences between call and aplly:
1, the first parameter, this is the same, refers to the current object
2, the second parameter is different: Call is a list of parameters, and apply is an array (arguments can also)

var per=new person ("Wu Feng Building", 25, "Wei Screen"); Output: "Wu Feng Building"
Per.say ();
var stu=new student ("mansion", 18);//output: "Mansion"
Stu.say ();
var tea=new teacher ("Narl", 16);//output: "Narl"
Tea.say ();

</script>
</body>


Ii. use of Call and apply (detailed introduction)

JS in the call and apply can be inherited, the only point of a different parameter, Func.call (FUNC1,VAR1,VAR2,VAR3) corresponding to the application of the wording: Func.apply (Func1,[var1,var2,var3]).

The explanation of call in the JS manual:

The code is as follows:
<span style= "font-size:18px" >call method
Invokes one method of an object, replacing the current object with another object.

Call ([thisobj[,arg1[, arg2[, [,. ArgN]]])

Parameters
Thisobj
Options are available. The object that will be used as the current object.

Arg1, Arg2,, ArgN
Options are available. The method parameter sequence will be passed.

Description
The call method can be used to invoke a method in place of another object. The call method can change the object context of a function from the initial context to a new object specified by Thisobj.

If the Thisobj parameter is not provided, then the Global object is used as the thisobj. </SPAN>


To put it simply, the function of these two functions is actually to change the object's internal pointer, that is, change the object's this point to the content. This is sometimes useful in the object-oriented JS programming process. The following is an example of apply, the two functions in the JS important role. Such as:

The code is as follows:
<span style= "font-size:18px" >functionPerson (name,age) {//define a class         This. name=name;//name         This. age=age;//Age         This. sayhello=function() {Alert ( This. Name)}; }      functionPrint () {//display the properties of a class         This. Funcname= "Print";  This. show=function(){              varmsg=[];  for(varKeyinch  This){                  if(typeof( This[key])! = "function") {Msg.push ([key,":", This[Key]]. Join ("")); }} alert (Msg.join (" "));      }; }      functionStudent (Name,age,grade,school) {//Student ClassPerson.apply ( This, arguments);//a better place than callPrint.apply ( This, arguments);  This. Grade=grade;//Grade         This. School=school;//School    }      varp1=NewPerson ("Bu culture", 80);      P1.sayhello (); vars1=NewStudent ("Baiyunfei", 40, 9, "Yuelu Academy");      S1.show ();      S1.sayhello (); alert (s1.funcname);</SPAN>

In addition, function.apply () has a prominent role in improving program performance:
Let's start with the Math.max () function, the Math.max can be followed by any parameter, and finally the maximum value in all parameters is returned.
Like what

The code is as follows:
<span style= "font-size:18px" >alert (Math.max (5,8));//8Alert (Math.max (5,7,9,3,1,6));//9    //But in many cases, we need to find the largest element in the array.     vararr=[5,7,9,1]; //alert (Math.max (arr)); This is not going to work. NaN    //to write like this .    functionGetmax (arr) {vararrlen=arr.length;  for(vari=0,ret=arr[0];i<arrlen;i++) {ret=Math.max (Ret,arr[i]); }          returnret; } alert (Getmax (arr)); //9    //change with apply, you can write this    functionGetMax2 (arr) {returnMath.max.apply (NULL, arr); } alert (GetMax2 (arr)); //9

The two pieces of code achieve the same goal, but GETMAX2 is elegant, efficient, and much simpler.

Another example is the push method of the array.
var arr1=[1,3,4];
var arr2=[3,4,5];
If we want to expand the arr2 and then add one to the arr1, and finally let arr1=[1,3,4,3,4,5]
Arr1.push (ARR2) is obviously not going to work. Because doing so will get [1,3,4,[3,4,5]]

We can only use a loop to go to one push (or Arr1.concat (ARR2), but the Concat method does not change arr1 itself)

var arrlen=arr2.length;
for (Var i=0;i<arrlen;i++) {
Arr1.push (Arr2[i]);
}

It's been so easy since I got the Apply

Array.prototype.push.apply (ARR1,ARR2); Now ARR1 is the desired result </SPAN>

Summary of methods of inheritance in JS (apply,call,prototype)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.