📜  JavaScript函数bind()

📅  最后修改于: 2020-09-27 06:16:11             🧑  作者: Mango

JavaScript Function bind()方法允许一个对象从其他对象借用方法而无需复制。

bind()方法的语法为:

func.bind(thisArg, arg1, ... argN)

在这里, func是一个函数 。


bind()参数

bind()方法采用:

  • thisArg作为func this参数提供的值。如果使用new 运算符创建绑定函数,则将其忽略。
  • arg1, ... argN (可选)-调用func时,将添加到绑定函数提供的参数之前的参数。

笔记:

  • setTimeout中使用thisArg时 ,原始值将转换为对象。
  • 如果未指定thisArg ,则执行范围的this视为thisArg

从bind()返回值
  • 返回具有指定this值和初始参数(如果提供)的给定函数的副本。

示例:使用bind()
this.x = 1; // "this" here is the global window object in browser

const obj = {
  x: 100,
  getX: function () {
    return this.x;
  },
};

console.log(obj.getX()); // 100

const retrieveX = obj.getX;
// the function gets invoked at the global scope
console.log(retrieveX()); // 1

//  Create a new function with 'this' bound to obj
//  global variable 'x' with obj's property 'x' are two separate entities
const boundGetX = retrieveX.bind(obj);

console.log(boundGetX()); // 100

输出

100
1
100

一旦一个方法是从物体通过单独的地方- this将丢失。使用原始对象从函数创建绑定函数可以很好地解决此问题


推荐读物: JavaScript函数call()