Call, apply in JavaScript

Source: Internet
Author: User

Call , apply in JavaScript Pager

Call in JavaScript calls a function that binds the value of this to the first parameter in the call parameter when the function is called.

varfunction(param, param2){    console.log(this);    console.log(param);    console.log(param2);    console.log("bye");    console.log(this.x)}t = {‘x‘112);

The result is:

Object {x:1}
1
2
Bye
1

Of course, we can also bind this value to a primitive value, calling the function:

bye.call(5, 1, 2);

The result is:

number {[[Primitivevalue]]: 5}
1
2
Bye

In non-strict mode, if we pass the value of the null,undefined and the original type to the This parameter, its this value will be replaced by global and there is a description in the MDN:

Thisarg
The value of this provided for the call to fun. Note that this may isn't the actual value seen by the method:if of the method is a function in non-strict mode code, NULL a nd undefined'll is replaced with the global object, and primitive values would be boxed.

The function of the call function is that we can set a different object when invoking the method, because its default object is the current object, and because of this, we can write the method only once, inherit the method in another object, and then call it without having to write the method again. An introduction to this method in MDN:

You can assign a different this object when the calling an existing function. This refers to the current object, the calling object. With call, you can write a method once and then inherit it in another object, without have to rewrite the method for the New object.

Scenario One: using call implementation inheritance (using call to chain constructors for a object)

 function Product(name, price) {   This. name = name; This. Price = Price;if(Price <0) {Throw Rangeerror(' cannot create product '+ This. Name +' with a negative price '); }return  This;} function food(name, price) {Product.call ( This, name, price); This. Category =' food ';} Food.prototype =Object. Create (Product.prototype); function Toy(name, price) {Product.call ( This, name, price); This. Category =' toy ';} Toy.prototype =Object. Create (Product.prototype);varCheese =NewFood (' feta ',5);varFun =NewToy (' robot ', +);

Food and toy use call to inherit the name and price of product, and then each has the category attribute.

Scenario Two: invoking an anonymous function using call (using the Invoke-to invocation an anonymous functions)

varAnimals = [{species:' Lion ', Name:' King '}, {species:' Whale ', Name:' Fail '}]; for(vari =0; i < animals.length; i++) {( function(i) {     This. Print = function() {Console.log (' # '+ i +"'+ This. Species +': '+ This. name); } This. print (); }). Call (Animals[i], i);}
Apply

Apply is almost identical to call, except that when you pass a parameter, apply passes an array (array) or an array-like object (Array-like object), which is invoked as follows:

fun.apply(this, [‘eat‘‘bananas‘]);fun.apply(thisnewArray(‘eat‘‘bananas‘));

Call, apply in JavaScript

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.