Use of call and apply

Source: Internet
Author: User

Use of call and apply

1. Passing parameters

The first parameter of call and apply is the object to be bound, the second parameter is different

The parameters used by call are variable parameters
The parameter used by apply is an array
function sum () {
var result = 0;
for (var i = 0; i < arguments.length; i++) {
Result + = Arguments[i];
}
return result;
}

function Obj (x, y) {
this.x = x;
This.y = y;
}

var obj = new obj (10, 20);//This is the way the function is directed to the obj

var result = Sum.call (obj, obj.x, obj.y);

var result2 = sun.apply (obj, [obj.x, Obj.y]);
Console.log (result);

Console.log (RESULT2);

2. Extended scope--determined by the scope range of the bound object

var student = {name: ' Zjy '};

var teacher = {name: ' Mr.zhao '};

function ShowName () {
Console.log (this.name);
}

Showname.call (student);
Showname.call (teacher);

3. Using call,apply to implement inheritance

function Animal () {
This.hoal = function () {
Console.log ("AAA");
}
}

function Cat () {
Animal.call (this);
}

var cat = new Cat ();
Cat.hoal ();

function Tiger () {
Cat.apply (this);
}

var tiger = new Tiger ();
Tiger.hoal ();

4. Simple simulation of call implementation

function sum () {
var result = 0;
for (var i = 0; i < arguments.length; i++) {
Result + = Arguments[i];
}
return result;
}

function Obj (x, y) {
this.x = x;
This.y = y;
}
Simple Call Simulation
Sum.mycall = function (obj) {
if (Arguments.length = = 0) {
Console.log ("must pass in a binding object");
} else {
Return this (Arguments[1], arguments[2]);
}
}
Console.log (Sum.mycall (obj, obj.x, obj.y));

For call and apply can realize the decoupling of code, easy to expand the program.

Use of call and apply

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.