The difference between the call, apply, and bind methods in JavaScript

Source: Internet
Author: User

In JavaScript, this direction is dynamic, it is possible to write a program, inadvertently destroy the point of this, so we need a technology that can be fixed the meaning of this, so there are call,apply and bind these three methods, To change the direction of this within the function body, because the function has the concept of "context at definition" and "runtime context" and "context can be changed."

Apply, call

Apply: Apply one method of an object to replace the current object with another object

Call: Invokes one method of an object, replacing the current object with another object

123456789101112131415 function person() {}person.prototype = {  attr: {age:18,sex:‘girl‘},  say: function() {    console.log("My age is "this.attr.age);    console.log("I am a "this.attr.sex);  }}varMarry = newperson();Marry.say();// My age is 18// I am a girl

Change Point

1234567891011121314151617181920 function person() {}person.prototype = {  attr: {age:18,sex:‘girl‘},  say: function() {    console.log("My age is "this.attr.age);    console.log("I am a "this.attr.sex);  }} xiaoming ={ attr : {age:20,sex:‘boy‘} };varMarry = newperson();Marry.say();Marry.say.call(xiaoming);// My age is 18// I am a girl// My age is 20// I am a boy

The common point

can be used instead of another object to invoke a method that changes the object context of a function from the initial context to the new object specified by Thisobj.

The difference

1, apply: There can be up to two parameters--the new this object and an array of Argarray. If you pass multiple arguments to the method, the arguments are written into the array, and of course, even if there is only one argument, it is written into the array. If Argarray is not a valid array or is not a arguments object, it will result in a TypeError. If none of the Argarray and Thisobj parameters are provided, then the Global object is used as a thisobj and cannot be passed any parameters.

1234567 fun.call(thisArg[, arg1[, arg2[, ...]]])functionf(x,y){  console.log(x+y);}f.call(null, 1, 1)//return 2

2, call: is a direct parameter list, mainly used in the JS object each method calls each other, so that the current this instance pointer is consistent, or in special cases need to change the this pointer. If the Thisobj parameter is not provided, then the Global object is used as the thisobj.

1234567 fun.apply(thisArg, [argsArray])functionf(x,y){  console.log(x+y);}f.call(null, [1,1])//return 2

Apply and call function, just pass in the form of the parameter list, where Thisarg is the context you want to specify, he can be any JavaScript object (everything in JavaScript object), call needs to pass parameters in order, and apply The parameter is placed in the array.

If the number of arguments to a function is not fixed, use call when your parameter is explicitly known, and use apply when unsure, and then pass the parameter push into the array. When the number of arguments is indeterminate, the inside of the function can also traverse all the arguments by arguments the array, so let's take a look at some usage

Code One

12345 vararray1 = [12 , "foo" , {name:"Joe"} , -2458];var array2 = ["Doe", 555 , 100];Array.prototype.push.apply(array1, array2);console.log(array1);//[12, "foo", Object, -2458, "Doe", 555, 100]

Code two

123 varnumbers = [5, 458 , 120 , -215 ];Math.max.apply(null,numbers);//458

Code Three

1234567 log (  "foo"   "Joe" }, -2458); function log () {    var  args = Array.prototype.slice.call (arguments);    args.unshift (    console.log.apply (console, args); }; //(APP) foo Object {name: "Joe"} -2458

Bind

1 fun.bind(thisArg[, arg1[, arg2[, ...]]])

Unlike the above, BIND returns a new function that changes this point, note that the new function is highlighted here, and it is not the same block memory address used previously, so when you need to reuse the function, you have to save it to a variable for the next call. The above two functions are the result of the execution of the return, that is, the call

Line, in addition, it is important to note that the first parameter in the BIND function will automatically become the default value of the parameter returned in the new function, then the formal invocation, only need to give the first parameter, except the remaining parameters.

12345678 functionf(x,y){  console.log(x+y);}f.call(null, [1,1])varnew_f = f.bind(null,1,1)//return new functionnew_f(1)//return 2

It should be stated that the Thisarg parameter in all the sample code above is replaced with NULL, in the case where the specified Thisarg object is not given, null and undefined under this point is the global object, that is, the JS Code execution Environment

Refer to the use and implementation of the bind () method in JavaScript

Apply, call, bind comparison

123456789101112131415 varobj = {bar: ‘Oops , this is a bad idea‘};varfoo = {    get: function() {        returnthis.bar;    }}varbind = foo.get.bind(obj) ,call = foo.get.call(obj) ,apply = foo.get.apply(obj);console.log(bind(),call,apply);console.log(bind,call,apply); console.log(typeofbind,typeofcall,typeofapply);console.log(typeofbind(),typeofcall,typeofapply);

To see the difference is not, the difference is that when you want to change the context is not immediately after the execution, but the callback execution, the use of the bind () method. and Apply/call immediately executes the function.

1234 apply 、 call 、bind 三者都是用来改变函数的this对象的指向的;apply 、 call 、bind 三者第一个参数都是this要指向的对象,也就是想指定的上下文;apply 、 call 、bind 三者都可以利用后续参数传参;bind是返回对应函数,便于稍后调用;apply、call则是立即调用

The difference between the call, apply, and bind methods 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.