Summary of several usages of JS inheritance (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

Copy CodeThe code is as follows:
<span style= "<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: Use prototype 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: Use prototype to get name: Hongru
Stu.intr ();//output: 5
</script>
</body>


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


3.call, apply implementation 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 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 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:

Copy CodeThe 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:

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 the properties of the 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 superior place 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, the Math.max can be followed by any parameter, and finally the maximum value in all parameters is returned.
Like what

Copy CodeThe code is 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)); This is not going to work. NaN

To 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

Change with 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 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 several usages of JS inheritance (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.