Home > Article > Web Front-end > The difference between call, apply and bind in js
In javascript, call, apply, and bind all exist to change the context when a function is running. In other words, they are to change the pointer of this inside the function body.
The difference between call, apply and bind in js
The difference between call, apply and bind can be found through the following Let’s look at examples.
var obj = { x: 81, }; var foo = { getX: function() { return this.x; } } console.log(foo.getX.bind(obj)()); //81 console.log(foo.getX.call(obj)); //81 console.log(foo.getX.apply(obj)); //81
The three outputs are all 81, but pay attention to the one using the bind() method. There are a pair of brackets after it.
In other words, the difference is that when you want to change the context environment and not execute it immediately, but callback execution, use the bind() method. Apply/call will execute the function immediately.
To summarize:
apply, call, and bind are all used to change the pointing of the this object of the function;
apply, call The first parameter of , bind is the object that this points to, that is, the context you want to specify;
apply, call, and bind can all use subsequent parameters to pass parameters;
bind returns the corresponding function for easy calling later;
apply and call call immediately.
This article comes from the js tutorial column, welcome to learn!
The above is the detailed content of The difference between call, apply and bind in js. For more information, please follow other related articles on the PHP Chinese website!