Home > Web Front-end > JS Tutorial > A brief discussion on bind() in JS

A brief discussion on bind() in JS

autoload
Release: 2021-04-15 13:58:11
Original
6321 people have browsed it

A brief discussion on bind() in JS

bind() is a built-in method of Function object. Their first parameter is used to change the calling method# Pointing to ##this. It should be noted that bind returns a new function so that it can be called later.

1. Grammar:

1

function.bind(thisArg[,arg1[,arg2[, ...]]])

Copy after login

  • thisArg: used as this when calling the bound function The parameter value passed to the target function. If the new operator is used to construct the bound function, this value is ignored. When using bind to create a function in setTimeout (provided as a callback), any primitive value passed as thisArg will be converted to an object. If the parameter list of the bind function is empty, or thisArg is null or undefined, this ## of the execution scope # will be treated as thisArg of the new function.

  • arg1,

    arg2, ...: When the target function is called, it is preset into the parameter list of the bound function parameters.

  • Return value: Returns a copy of the original function and has the specified this Values ​​and Initial parameters.

2. Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<script>

        //这是一个函数

        function hello(name) {

            //this:执行上下文,程序的运行环境

            //this当前是window,全局

            this.name=name;

            console.log(this.name);

        }

        hello("天才上单");

 

        //bind()可以改变函数中的this指向

 

        //这是一个对象

        const obj={

            name :"天鹏下凡",

        };

 

        //bind()只绑定不执行

         let f1=hello.bind(obj,"那就这样吧!");

         console.log(f1());

 </script>

Copy after login

3. Output

1

2

3

天才上单   

那就这样吧!

undefined

Copy after login
Recommended: "

2021 js interview questions and answers (large summary)

"

The above is the detailed content of A brief discussion on bind() in JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
js
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template