Js in Apply and call

Source: Internet
Author: User

Recently see JS always encounter object substitution, not very understanding of JS in the use of call and apply, here a glance, just understand its usage:

Apply definition : applies one method of an object, replacing the current object with another object. Apply ([Thisobj[,argarray]])

Call definition : invokes one method of an object, replacing the current object with another object. call ([thisobj[,arg1[, arg2[, [,. ArgN] ]])

From the above can be seen in fact, their usage is almost the same, the only difference is that when the invocation, apply the Parameter form is the form of an array, and call does not have this requirement;

When your parameter is clearly known quantity, use Call, and when unsure, use apply, and then pass the parameter push into the array;

For specific usage, take a look at the following example:

function Cat () {}cat.prototype={food    : ' Fish ',    say:function () {        alert ("I Love" +this.food);}    }  var blackcat = new Cat;  Blackcat.say ();  var dog={food: "Bone"};  BlackCat.say.call (dog);

The effect of the output is as follows:

As can be seen from the above:

to see that call and apply are in order to change this dynamically, when an object does not have a method, but others have, we can use call or apply the method of other objects to operate.

We have an object dog= {food: "Bone"}, we do not want to redefine it say method, then we can use call or Apply Blackcat say method: BlackCat.say.call (Whitedog);

There is an idea of the inheritance in OOP.

The above is just on the internet to see the great God's explanation, more easily understand the text, in this writing, and we encourage each other, I hope you provide more understanding ...

Js in Apply and call

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.