Several usage summaries of the inheritance in JS (apply,call,prototype) _javascript skills

Source: Internet
Author: User
Tags ming

One, the object inheritance in JS

There are three ways of inheriting in JS

1.js Prototype (prototype) Implementation inheritance

Copy Code code 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 Xiao", 21);
Per.sayhello (); Output: Using prototypes to get Name: Ma Xiao


function Student () {}
Student.prototype=new person ("Hongru", 21);
var stu=new Student ();
student.prototype.grade=5;
Student.prototype.intr=function () {
alert (This.grade);
}
Stu.sayhello ()//output: Using Prototypes to get Name: Hongru
STU.INTR ()//output: 5
</script>
</body>

2. Constructor implementation inheritance
Copy Code code 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 Jiansen");
Parent.sayparent (); Output: "Parent: Jiang Jiansen"
var child=new child ("Li Ming", 24); Output: "Child: Li Ming age:24"
Child.saychild ();
</script>
</body>

3.call, apply to implement inheritance
Copy Code code 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 mode
function Student (name,age) {
Person.call (This,name,age);
}

Apply method
function Teacher (name,love) {
Person.apply (This,[name,love]);
Person.apply (this,arguments); The same effect as the last sentence, arguments
}

The similarities and differences of 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; 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 ("Cao Yu", 18);//output: "Cao Yu"
Stu.say ();
var tea=new teacher ("Qin Jie", 16);//output: "Qin Jie"
Tea.say ();

</script>
</body>

Ii. use of Call and apply (detailed introduction)

JS call and apply can be implemented inheritance, the only point of different parameters, Func.call (FUNC1,VAR1,VAR2,VAR3) corresponding apply to be written as: Func.apply (FUNC1,[VAR1,VAR2,VAR3)).

An explanation of call in the JS manual:

Copy Code code as follows:

<span style= "font-size:18px" >call method
Invokes one of the object's methods to replace the current object with another object.

Call ([thisobj[,arg1[, arg2[, [,. argn]]]]

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

Arg1, Arg2, argn.
Options available. A sequence of method parameters is passed.

Description
The call method can be used to invoke 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 supplied, the Global object is used as a thisobj. </SPAN>

To put it simply, the function of these two functions is to change the internal pointer of an object, that is, to change the object's this point. This is sometimes useful in the object-oriented JS programming process. The following takes apply as an example, say these two functions in JS important role. Such as:
Copy Code code 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 () {//Show properties of Class
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); a place superior to call
Print.apply (this,arguments);
This.grade=grade; Grade
This.school=school; School
}
var p1=new person ("Bu culture", 80);
P1.sayhello ();
var s1=new Student ("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, Math.max can be followed by any argument, and finally return the maximum value in all parameters.
Like what
Copy Code code as follows:

<span style= "font-size:18px" >alert (Math.max (5,8)); 8
Alert (Math.max (5,7,9,3,1,6)); 9

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

var arr=[5,7,9,1];
Alert (Math.max (arr)); It's not going to work. NaN

To write 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

Change to apply, you can write this
function GetMax2 (arr) {
Return Math.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 an array.
var arr1=[1,3,4];
var arr2=[3,4,5];
If we want to expand the arr2, and then one by one append to the arr1, finally let arr1=[1,3,4,3,4,5]
Arr1.push (ARR2) is clearly not a good one. Because doing so will get [1,3,4,[3,4,5]]

We can only use one loop to go one push (of course we can also use Arr1.concat (ARR2), but 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 ever since the Apply

Array.prototype.push.apply (ARR1,ARR2); Now ARR1 is the result of the want </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.