The difference between call, apply and bind in js

angryTom
Release: 2020-02-12 16:02:26
Original
4397 people have browsed it

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 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
Copy after login

The three outputs are all 81, but pay attention to the one using the bind() method. There are a pair ofbracketsafter 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 thejs tutorialcolumn, 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!