Summary of several inherited usage methods in js (apply, call, prototype)

Source: Internet
Author: User

1. Object Inheritance in js

There are three inheritance methods in js:

1. prototype inheritance
Copy codeThe Code is as follows:
<SPAN style = "BACKGROUND-COLOR: # ffffff"> <SPAN style = "FONT-SIZE: 18px"> <Body>
<Script type = "text/javascript">
Function Person (name, age ){
This. name = name;
This. age = age;
}
Person. prototype. sayHello = function (){
Alert ("use prototype to get Name:" + this. name );
}
Var per = new Person ("Ma Xiaoqian", 21 );
Per. sayHello (); // output: Use the prototype to get the Name: Ma Xiaoqian


Function Student (){}
Student. prototype = new Person ("Hong Ru Tong", 21 );
Var stu = new Student ();
Student. prototype. grade = 5;
Student. prototype. intr = function (){
Alert (this. grade );
}
Stu. sayHello (); // output: Use the prototype to obtain the Name: Hong ruotong.
Stu. intr (); // output: 5
</Script>
</Body>
</Html> </SPAN>

2. constructor implementation inheritance
Copy codeThe Code is as follows:
<SPAN style = "FONT-SIZE: 18px"> <Body>
<Script type = "text/javascript">
Function Parent (name ){
This. name = name;
This. sayParent = function (){
Alert ("Parent:" + this. name );
}
}

Function Child (name, age ){
This. tempMethod = Parent;
This. tempMethod (name );
This. age = age;
This. sayChild = function (){
Alert ("Child:" + this. name + "age:" + this. age );
}
}

Var parent = new Parent ("Jiang jianchen ");
Parent. sayParent (); // output: "Parent: Jiang jianchen"
Var child = new Child ("Li Ming", 24); // output: "Child: Li Ming age: 24"
Child. sayChild ();
</Script>
</Body>
</Html> </SPAN>

3. call and apply implement inheritance
Copy codeThe Code is as follows:
<SPAN style = "FONT-SIZE: 18px"> <Body>
<Script type = "text/javascript">
Function Person (name, age, love ){
This. name = name;
This. age = age;
This. love = love;
This. say = function say (){
Alert ("name:" + name );
}
}

// Call Method
Function student (name, age ){
Person. call (this, name, age );
}

// Apply Method
Function teacher (name, love ){
Person. apply (this, [name, love]);
// Person. apply (this, arguments); // same effect as the sentence, arguments
}

// Similarities and differences between call and aplly:
// 1. The first parameter "this" is the same as the current object.
// 2. The second parameter is different: call is a list of parameters one by one; apply is an array (arguments can also be)

Var per = new Person ("Wu fenglou", 25, "Wei "); // output: "Wu fenglou"
Per. say ();
Var stu = new student ("Cao Yu", 18); // output: "Cao Yu"
Stu. say ();
Var tea = new teacher ("Qin Jie", 16); // output: "Qin Jie"
Tea. say ();

</Script>
</Body>
</Html> </SPAN>

Ii. call and apply usage (details)

In js, both call and apply can be inherited. The unique parameter is different. the apply method for call (func1, var1, var2, var3) is: func. apply (func1, [var1, var2, var3]).

Explanation of call in the JS manual:
Copy codeThe Code is as follows:
<SPAN style = "FONT-SIZE: 18px"> call Method
Call a method of one object to replace the current object with another object.

Call ([thisObj [, arg1 [, arg2 [, [,. argN])

Parameters
ThisObj
Optional. Will be used as the object of the current object.

Arg1, arg2, and argN
Optional. The method parameter sequence will be passed.

Description
The call method can be used to call a method instead of another object. The call method can change the object context of a function from the initial context to the new object specified by thisObj.

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

To put it simply, these two functions are actually used to change the internal pointer of an object, that is, to change the content that this points. This is sometimes useful in Object-Oriented js programming. The following uses apply as an example to describe the important roles of these two functions in js. For example:
Copy codeThe Code is as follows:
<SPAN style = "FONT-SIZE: 18px"> function Person (name, age) {// define a class
This. name = name; // name
This. age = age; // age
This. sayhello = function () {alert (this. name )};
}
Function Print () {// display class attributes
This. funcName = "Print ";
This. show = function (){
Var msg = [];
For (var key in this ){
If (typeof (this [key])! = "Function "){
Msg. push ([key, ":", this [key]. join (""));
}
}
Alert (msg. join (""));
};
}
Function Student (name, age, grade, school) {// Student Class
Person. apply (this, arguments); // superior to call
Print. apply (this, arguments );
This. grade = grade; // grade
This. school = school; // school
}
Var p1 = new Person ("Bu Kaihua", 80 );
P1.sayhello ();
Var s1 = new Student ("baiyunfei", "Yuelu Emy ");
S1.show ();
S1.sayhello ();
Alert (s1.funcName); </SPAN>

In addition, Function. apply () plays an outstanding role in improving program performance:
Let's start with the Math. max () function. Math. max can be followed by any parameter and return the maximum value among all parameters.
For example
Copy codeThe Code is as follows:
<SPAN style = "FONT-SIZE: 18px"> alert (Math. max (5, 8); // 8
Alert (Math. max (,); // 9

// However, in many cases, we need to find the largest element in the array.

Var arr = [5, 7, 9, 1];
// Alert (Math. max (arr); // This is not acceptable. NaN

// Write like this
Function getMax (arr ){
Var arrLen = arr. length;
For (var I = 0, ret = arr [0]; I <arrLen; I ++ ){
Ret = Math. max (ret, arr [I]);
}
Return ret;
}

Alert (getMax (arr); // 9

// Replace apply. You can write it like this.
Function getMax2 (arr ){
Return Math. max. apply (null, arr );
}

Alert (getMax2 (arr); // 9

// The two pieces of code achieve the same purpose, but getMax2 is elegant, efficient, and concise.

// Another example is the array push method.
Var arr1 = [1, 3, 4];
Var arr2 = [3, 4, 5];
// If we want to expand arr2, append it to arr1 one by one, and finally let arr1 = [1, 3, 4, 5]
// Arr1.push (arr2) obviously does not work. In this case, [, 4, [, 5] is obtained.

// We can only use one loop to push one by one (of course, arr1.concat (arr2) can also be used, but the concat method does not change the arr1 itself)

Var arrLen = arr2.length;
For (var I = 0; I <arrLen; I ++ ){
Arr1.push (arr2 [I]);
}

// Things have become so simple with Apply

Array. prototype. push. apply (arr1, arr2); // now arr1 is the expected result </SPAN>

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.