js:bind、call、apply的区别

概念

bind

语法:

function.bind(thisArg[, arg1[, arg2[, ...]]])
参数 说明
thisArg 调用绑定函数时作为 this 参数传递给目标函数的值。 如果使用new运算符构造绑定函数,则忽略该值。当使用 bind 在 setTimeout 中创建一个函数(作为回调提供)时,作为 thisArg 传递的任何原始值都将转换为 object。如果 bind 函数的参数列表为空,或者thisArg是null或undefined,执行作用域的 this 将被视为新函数的 thisArg。
arg1, arg2, … 参数

返回值:
返回一个原函数的拷贝,并拥有指定的 this 值和初始参数。

call

语法:

function.call(thisArg, arg1, arg2, ...)
参数 说明
thisArg 可选的。在 function 函数运行时使用的 this 值。请注意,this可能不是该方法看到的实际值:如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动替换为指向全局对象,原始值会被包装。
arg1, arg2, … 指定的参数列表。

返回值:
使用调用者提供的 this 值和参数调用该函数的返回值。若该方法没有返回值,则返回 undefined。

apply

语法:

func.apply(thisArg, [argsArray])
参数 说明
thisArg 必选的。在 func 函数运行时使用的 this 值。请注意,this可能不是该方法看到的实际值:如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动替换为指向全局对象,原始值会被包装。
arg1, arg2, … 可选的。一个数组或者类数组对象,其中的数组元素将作为单独的参数传给 func 函数。如果该参数的值为 null 或 undefined,则表示不需要传入任何参数。

返回值:
调用有指定this值和参数的函数的结果。

实践

bind

// 在浏览器中,this 指向全局的 "window" 对象
this.name = '全局名称';
// 局部作用域中 this 指向局部的对象
const module = {
    
    
  name: '局部名称',
  getName: function() {
    
     return this.name; }
};

// 返回 '局部名称' - 因为函数是在局部作用域中调用的
const data = module.getName();
console.log('data', data)

// 返回 '全局名称' - 因为函数是在全局作用域中调用的
const getGlobalName = module.getName;
console.log('data1', getGlobalName());

// 返回 '局部名称' - 新手可能会将全局变量 name 与 module 的属性 name 混淆
// 创建一个新函数,把 'this' 绑定到 module 对象
const getLocalName = getGlobalName.bind(module);
console.log('data2', getLocalName());

在这里插入图片描述

call

function Product(name, price) {
    
    
  this.name = name;
  this.price = price;
}

function Food(name, price) {
    
    
  // 相当于调用了Product并传入了name, price两个参数
  Product.call(this, name, price);
  this.category = 'food';
}

console.log(new Food('cheese', 5).name);
// expected output: "cheese"

apply

function Product(name, price) {
    
    
  this.name = name;
  this.price = price;
}

function Food(name, price) {
    
    
  // 相当于调用了Product并传入了name, price两个参数
  Product.apply(this, [name, price]);
  this.category = 'food';
}

console.log(new Food('cheese', 5).name);
// expected output: "cheese"

总结

  • call 与 apply 类似,区别就是 call 接受的是参数列表,而 apply 接受的是一个参数数组。
  • bind 与(call 和 apply)相似,其作用都是用于改变函数内部 this 的指向。但是不同的是 call 与 apply 是立即执行函数而 bind 函数是将函数返回。

猜你喜欢

转载自blog.csdn.net/weixin_43972437/article/details/124785786
今日推荐