Call and apply in JavaScript

Source: Internet
Author: User

Call and apply in JavaScript
Call and apply in JavaScriptCall

The call in JavaScript calls a function. When calling a function, bind the value of this to the first parameter in the call parameter.

var bye = function(param, param2){    console.log(this);    console.log(param);    console.log(param2);    console.log("bye");    console.log(this.x)}t = {'x': 1};bye.call(t, 1, 2);

The result is:

Object {x: 1}
1
2
Bye
1

Of course, we can also bind this value to an original value and call the above function:

bye.call(5, 1, 2);

The result is:

Number {[[PrimitiveValue]: 5}
1
2
Bye

In non-strict mode, if we pass null, undefined, and original type values to this parameter, the value of this will be replaced by global. In MDN, it is described as follows:

ThisArg
The value of this provided for the call to fun. note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.

The purpose of the call function is to set a different object when calling a method, because the default object is the current object. Because of this, we can write this method only once, inherit the method from another object and call it without having to write it again. Introduction to this method in MDN:

You can assign a different this object when calling an existing function. this refers to the current object, the calling object. with call, you can write a method once and then inherit in another object, without having to rewrite the method for the new object.

Application Scenario 1:Use call to implement inheritance (Using call to chain constructors for an 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);var cheese = new Food('feta', 5);var fun = new Toy('robot', 40);

Food and Toy use call to inherit the Product name and price, and then each has a category attribute.

Application Scenario 2:Call an anonymous function (Using call to invoke an anonymous function)

var animals = [  { species: 'Lion', name: 'King' },  { species: 'Whale', name: 'Fail' }];for (var i = 0; i < animals.length; i++) {  (function(i) {    this.print = function() {      console.log('#' + i + ' ' + this.species                  + ': ' + this.name);    }    this.print();  }).call(animals[i], i);}
Apply

The apply method is almost identical to the call method, but when passing a parameter, the apply method transmits an array or an object similar to an array (array-like object). The call method is as follows:

fun.apply(this, ['eat', 'bananas']);fun.apply(this, new Array('eat', 'bananas'));

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.