JavaScript call (), apply () and bind ()?

This article was translated from: Javascript call () & apply () vs bind ()?

I already know that applyand callare similar functions which set this(context of a function). I already know that applyand callare thissimilar functions (set of context).

The difference is with the way we send the arguments (manual vs array) The difference is with the way we send the arguments (manual vs array )

Question: Question:

Should the when the I use at The But bind()Method,? But when I should use bind()methods?

var obj = {
  x: 81,
  getX: function() {
    return this.x;
  }
};

alert(obj.getX.bind(obj)());
alert(obj.getX.call(obj));
alert(obj.getX.apply(obj));

jsbin jsbin


#1st Floor

Reference: https://stackoom.com/question/12qYL/JavaScript-call- and apply- and bind


#2nd Floor

Use .bind()when you want that function to later be called with a certain context, useful in events. When you want to call this function in a specific context in the future, please use it .bind(), which is useful in events. Use .call()or .apply()when you want to invoke the function immediately, and modify the context. To use the function immediately and modify the context , use .apply() .call()or .apply().

Call / apply call the function immediately, whereas bindreturns a function that, when later executed, will have the correct context set for calling the original function. The call / app immediately calls the function and bindreturns a function, when the function is executed later, Will have the correct context set to call the original function. This way you can maintain context in async callbacks and events. This way, you can maintain context in asynchronous callbacks and events.

I do this a lot: I often do this:

function MyObject(element) {
    this.elm = element;

    element.addEventListener('click', this.onClick.bind(this), false);
};

MyObject.prototype.onClick = function(e) {
     var t=this;  //do something with [t]...
    //without bind the context of this function wouldn't be a MyObject
    //instance as you would normally expect.
};

I use it extensively in Node.js for async callbacks that I want to pass a member method for, but still want the context to be the instance that started the async action. I use it extensively for asynchronous callbacks in Node.js, I want to pass a member method to it, but still want the context to be an instance of starting an asynchronous operation.

A simple, naive implementation of bind would be like: A simple, simple bind implementation is:

Function.prototype.bind = function(ctx) {
    var fn = this;
    return function() {
        fn.apply(ctx, arguments);
    };
};

There is more to it (like passing other args), but you can read more about it and see the real implementation on the MDN . It has more features (just like passing other args), but you can read more Regarding its content, and check the actual implementation on MDN .

Hope this helps. Hope this helps .


#3rd floor

Android.permission at The value to the SET IT for thiswork of the Independent of How Called at The IS function. It allows you to set values, thisindependent of how the function is called. This is very useful when working with callbacks: This is very useful when using callbacks:

  function sayHello(){
    alert(this.message);
  }

  var obj = {
     message : "hello"
  };
  setTimeout(sayHello.bind(obj), 1000);

Achieve Result The Same with the To callWould look like the this: with the callsame result is achieved looks like this:

  function sayHello(){
    alert(this.message);
  }

  var obj = {
     message : "hello"
  };
  setTimeout(function(){sayHello.call(obj)}, 1000);

#4th floor

WE have have the ASSUME multiplicationfunction Suppose we have a multiplicationfunction

function multiplication(a,b){
console.log(a*b);
}

Lets create some standard functions using bind Let us use bindto create some standard functions

var multiby2 = multiplication.bind(this,2);

Now multiby2 (b) is equal to multiplication (2, b); now multiby2 (b) is equal to multiplication (2, b)

multiby2(3); //6
multiby2(4); //8

What if I pass both the parameters in bind if I passed two parameters in the binding how do

var getSixAlways = multiplication.bind(this,3,2);

Now getSixAlways () is equal to multiplication (3,2); now getSixAlways () is equal to multiplication (3,2);

getSixAlways();//6

even passing parameter returns 6; even passing parameter returns 6; getSixAlways(12); //6

var magicMultiplication = multiplication.bind(this);

This create a new multiplication function and assigns it to magicMultiplication. This will create a new multiplication function and assign it to magicMultiplication.

Oh no, we are hiding the multiplication functionality into magic Multiplication. Oh no, we are hiding the multiplication functionality into magic Multiplication.

Calling magicMultiplicationreturns A A blank function b() call magicMultiplicationreturns a blankfunction b()

on execution it works fine magicMultiplication(6,5); //30 when executed, it can workmagicMultiplication(6,5); //30 magicMultiplication(6,5); //30

How about call and apply? How about call and apply ?

magicMultiplication.call(this,3,2); //6

magicMultiplication.apply(this,[5,2]); //10

Simple words the In, bindCreates The function, calland applyExecutes The function whereas applythe expects The Parameters Array in simple terms, bindcreate a function, calland applythe function is executed and the applyparameters of the desired array


#5th Floor

They all attach this into function (or object) and the difference is in the function invocation (see below). They are all attached to this function (or object) except for the function call (see below).

call attaches this into function and executes the function immediately: call the function attached to this function and execute immediately:

var person = {  
  name: "James Smith",
  hello: function(thing) {
    console.log(this.name + " says hello " + thing);
  }
}

person.hello("world");  // output: "James Smith says hello world"
person.hello.call({ name: "Jim Smith" }, "world"); // output: "Jim Smith says hello world"

the bind attaches the this INTO IT function and Needs to BE the Invoked separately like the this: the binding is attached to this function and it needs to be separated from this call:

var person = {  
  name: "James Smith",
  hello: function(thing) {
    console.log(this.name + " says hello " + thing);
  }
}

person.hello("world");  // output: "James Smith says hello world"
var helloFunc = person.hello.bind({ name: "Jim Smith" });
helloFunc("world");  // output: Jim Smith says hello world"

or like this: or like this:

...    
var helloFunc = person.hello.bind({ name: "Jim Smith" }, "world");
helloFunc();  // output: Jim Smith says hello world"

apply IS Similar to call the except that Takes AN IT INSTEAD Array-like Object The arguments of Listing OUT AT A One Time: apply the call is similar except that apply similar array, rather than a time parameter lists:

function personContainer() {
  var person = {  
     name: "James Smith",
     hello: function() {
       console.log(this.name + " says hello " + arguments[1]);
     }
  }
  person.hello.apply(person, arguments);
}
personContainer("world", "mars"); // output: "James Smith says hello mars", note: arguments[0] = "world" , arguments[1] = "mars"                                     

#6th floor

Both Function.prototype.call()and Function.prototype.apply()call a function with a given thisvalue, and return the return value of that function. And use a given value to call a function and return the return value of the function.Function.prototype.call()Function.prototype.apply()this

Function.prototype.bind(), on the other hand, creates a new function with a given thisvalue, and returns that function without executing it. On the other hand, creates a new function with a given value and returns the function without executing it .Function.prototype.bind()this

So, let's take a function that looks like this: So let's take a function that looks like this :

var logProp = function(prop) {
    console.log(this[prop]);
};

Now, let's take an object that looks like this: Now, let's look at an object that looks like this :

var Obj = {
    x : 5,
    y : 10
};

We can bind our function to our object like this: We can bind our function to our object like this :

Obj.log = logProp.bind(Obj);

Now, WE CAN RUN Obj.logAnywhere in Our code: Now, we can run anywhere in the code Obj.log:

Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10

Where it really gets interesting, is when you not only bind a value for this, but also for for its argument prop: The really interesting thing is that you not only thisbind a value but also its parameters prop:

Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');

We can now do this: We can now do this :

Obj.logX(); // Output : 5
Obj.logY(); // Output : 10
Published 0 original articles · praised 75 · 560,000 views +

Guess you like

Origin blog.csdn.net/w36680130/article/details/105447068