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

A brief discussion on bind() in JS

autoload
autoloadOriginal
2021-04-06 15:09:176305browse

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:

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

  • 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:

<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>

3. Output

天才上单    
那就这样吧!
undefined
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!

Statement:
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