Call apply and bind methods in javascript, applybind

Source: Internet
Author: User

Call apply and bind methods in javascript, applybind

In JavaScript, call, apply, and bind are the three methods that come with the Function object. In this article, three methods are described in detail through the application of several scenarios.

Call ()

The call () method calls a function or method when a specified this value and several specified parameter values are used.

When calling a function, you can assign a different this object. This references the current object, that is, the first parameter of the call method.

By using the call method, you can borrow methods from another Object, such as Object. prototype. toString. call ([]) is an Array Object that uses methods on the Object.

Syntax fun. call (thisArg [, arg1 [, arg2 [,...])
ThisArg
This value specified when the fun function is running. Note the following situations:

(1) do not pass, or pass null, undefined. this in the function points to the window object.
(2) Pass the function name of another function. this in the function points to the reference of this function, not necessarily the true this value during function execution.
(3) If the value is the original value (Number, String, Boolean), this will point to the automatically wrapped object of the original value, such as String, Number, Boolean
(4) pass an object. this in the function points to this object.

Arg1, arg2 ,...
The list of specified parameters.

Example
Example

Function a () {// output function a's this object console. log (this) ;}// defines the function bfunction B () {}var obj = {name: 'This is a loggern'}; // defines the object obja. call (); // wa. call (null); // calls wa. call (undefined); // calls wa. call (1); // Numbera. call (''); // Stringa. call (true); // Booleana. call (B); // function B () {}. call (obj); // Object

Use the call method to call an anonymous function and specify the context's this

In the following example, when the greet method is called, The this value of this method is bound to the I object.

Function greet () {var reply = [this. person, 'is a lightweight', this. role]. join (''); console. log (reply);} var I = {function greet () {var reply = [this. person, 'is a lightweight', this. role]. join (''); console. log (reply);} var I = {person: 'jslite. io ', role: 'javascript library. '}; Greet. call (I); // JSLite. io is a lightweight Javascript library. Person: 'jslite. io ', role: 'javascript library. '}; Greet. call (I); // JSLite. io is a lightweight Javascript library.

Call an anonymous function using the call Method

In the for loop in the following example, an anonymous function is created, and each array element is executed as the specified this value by calling the call method of the function. The main purpose of this anonymous function is to add a print method to each array element object. This print method can print the correct index number of each element in the array. Of course, it is not necessary to pass the array element as the this value into the anonymous function (normal parameters are acceptable) to demonstrate the call usage.

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);}//#0 Lion: King//#1 Whale: Fail

Call function parameters using the call Method

Var a = {name: 'jslite. io ', // defines the attribute say: function () {// defines the console of method. log ("Hi, I'm function! ") ;}}; Function B (name) {console. log ("Post params:" + name); console. log ("I'm" + this. name); this. say ();} B. call (a, 'test'); // Post params: test // I'm onepixel // I'm function!

Apply ()

The syntax is almost identical to that of the call () method. The only difference is that the second parameter of apply must be an array (or a class array object) containing multiple parameters ). This feature of apply is very important,

When calling an existing function, you can specify an this object for it. This indicates the current object, that is, the object that is calling this function. With apply, you can write this method only once and inherit it from another object, instead of re-writing this method in the new object.

Syntax: fun. apply (thisArg [, argsArray])
Note: Chrome 14 and Internet Explorer 9 still do not accept Class array objects. If an array object is input, an exception is thrown.

Parameters
ThisArg

Same as the thisArg parameter of call.

ArgsArray

An array or a class array object. The array elements are passed as independent parameters to the fun function. If the value of this parameter is null or undefined, it indicates that no parameter is required. The class array object can be used from ECMAScript 5.

Example

function jsy(x,y,z){ console.log(x,y,z);}jsy.apply(null,[1,2,3]); // 1 2 3

Example of link constructor using apply

You can use apply to give an object link constructor, similar to Java. in the following example, we will create a global Function called construct to enable you to use a class array object rather than a parameter list in the construct.

Function.prototype.construct = function(aArgs) { var fConstructor = this,  fNewConstr = function() {  fConstructor.apply(this, aArgs);  }; fNewConstr.prototype = fConstructor.prototype; return new fNewConstr();};function MyConstructor () { for (var nProp = 0; nProp < arguments.length; nProp++) {  console.log(arguments,this)  this["property" + nProp] = arguments[nProp]; }}var myArray = [4, "Hello world!", false];var myInstance = MyConstructor.construct(myArray);console.log(myInstance.property1);    // logs "Hello world!"console.log(myInstance instanceof MyConstructor); // logs "true"console.log(myInstance.constructor);    // logs "MyConstructor"

Use apply and built-in functions

The clever apply method allows you to use built-in functions in some tasks that originally need to be written to traverse array variables. In the following example, we will use Math. max/Math. min to find the Maximum/minimum value in an array.

// An array object with the maximum and minimum numeric values var numbers = [5, 6, 2, 3, 7];/* use Math. min/Math. max applies */var max = Math in apply. max. apply (null, numbers); // Math is generally used. max (5, 6 ,..) or Math. max (numbers [0],...) find the maximum value var min = Math. min. apply (null, numbers); // normally, we will find the maximum or minimum values of the numbers. // compare them with the preceding chestnuts. Doesn't the following seem uncomfortable? Max =-Infinity, min = + Infinity; for (var I = 0; I <numbers. length; I ++) {if (numbers [I]> max) max = numbers [I]; if (numbers [I] <min) min = numbers [I];}

The parameter array is segmented and passed in cyclically

function minOfArray(arr) { var min = Infinity; var QUANTUM = 32768; for (var i = 0, len = arr.length; i < len; i += QUANTUM) { var submin = Math.min.apply(null, arr.slice(i, Math.min(i + QUANTUM, len))); console.log(submin, min) min = Math.min(submin, min); } return min;}var min = minOfArray([5, 6, 2, 3, 7]);

Bind

The bind () function creates a new function (called the binding function)

Bind is a new method of ES5.
Passing parameters is similar to calling or apply.
Does not execute the corresponding function, call or apply will automatically execute the corresponding function
Returns the reference to the function.
Syntax fun. bind (thisArg [, arg1 [, arg2 [,...])

The following example: When a webpage is clicked, EventClick is triggered and JSLite. io p1 p2 is output. this indicates that this in EventClick is changed to obj object by bind. If you set EventClick. bind (obj, 'p1', 'p2') to EventClick. call (obj, 'p1', 'p2'), the page will directly output JSLite. io p1 p2

Var obj = {name: 'jslite. io '};/*** Add a click event listener to the document and bind the EventClick function * to set this of EventClick to obj using the bind method, and pass the parameters p1, p2 */document. addEventListener ('click', EventClick. bind (obj, 'p1', 'p2'), false); // triggered when a webpage is clicked and run function EventClick (a, B) {console. log (this. name, // JSLite. io a, // p1 B // p2)} // JSLite. io p1 p2

Compatible

If (! Function. prototype. bind) {Function. prototype. bind = function (oThis) {if (typeof this! = "Function") {// closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError ("Function. prototype. bind-what is trying to be bound is not callable ");} var returns GS = Array. prototype. slice. call (arguments, 1), fToBind = this, // this points to the target function fNOP = function () {}, fBound = function () {return fToBind. apply (this instanceof fNOP? This // this Is The new obj: oThis | this, // If the passed oThis is invalid, use the fBound caller as this // merge the parameters passed through bind and the parameters passed during the call, and pass them as the final parameters to the callback Gs. concat (Array. prototype. slice. call (arguments) ;}; fNOP. prototype = this. prototype; // copy the prototype object of the target function to the new function, because the target function may be used as a constructor using fBound. prototype = new fNOP (); // return the reference of fBond. return fBound is called externally as needed ;};}

Compatible example from: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility

Application Scenario: Inheritance

Function Animal (name, weight) {this. name = name; this. weight = weight;} function Cat () {// pass this in the call as the thisArgs parameter // this in the Animal method points to this in Cat // so this in Animal points to the cat object // defined in Animal with the name and weight attributes, it is equivalent to defining these attributes in cat. // The cat object has the attributes defined in Animal to achieve the purpose of Animal inheritance. call (this, 'cat', '50'); // Animal. apply (this, ['cat', '50']); this. say = function () {console. log ("I am" + this. name + ", my weight is" + this. weight) ;}} // when cat is generated through the new operator, this in Cat points to the cat object var cat = new Cat (); cat. say (); // output => I am cat, my weight is 50

Prototype Extension

Extend and customize methods on the prototype functions, so that native functions are not contaminated. For example, we extend a forEach in Array.

Function test () {// checks whether arguments is an Array instance console. log (arguments instanceof Array, // false Array. isArray (arguments) // false); // checks whether arguments has the forEach method console. log (arguments. forEach); // undefined // apply the forEach in the Array to the arguments Array. prototype. forEach. call (arguments, function (item) {console. log (item); // 1 2 3 4});} test (1, 2, 3, 4 );

Articles you may be interested in:
  • Js apply/call/caller/callee/bind usage and Difference Analysis
  • Comparison and Analysis of call, apply, and bind usage in javascript
  • Usage of call (), apply (), and bind () in javascript
  • Enable the usage of apply, call, and bind in Javascript
  • Learn how to call (), apply (), bind () and callback in javascript.
  • Usage of call (), apply (), and bind () in javascript
  • Call, apply, and bind in javascript

Related Article

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.