apply,bing,call解析

3 篇文章 0 订阅

this 指向

this 指向:this 永远指向最后调用它的那个对象

func.apply()

func.apply(thisArg,[argsArray])

thisArg:必填项,传入一个需要 this 指向的对象,否则 this 指向 Window

argsArray: 选填项,传入个数组

// 实例一
// arguments 是一个对应于传递给函数的参数的类数组对象。
// 使用apply()传递数组时,在形参的位置如果只写一个参数时,在方法里面输出数组里面的1个元素
function isApply() {
  console.log(arguments);
  return this;
}
let obj = {
  name: "张三",
  age: 18,
  sex: "man",
};
console.log(isApply("aaa")); //this指向window
console.log(isApply.apply(obj, [{ name: "aaa" }, { name: "bbb" }])); //this指向obj对象   //console.log(arr);  输出 [{ name: "aaa" }, { name: "bbb" }]
console.log(isApply.apply(obj, ["aaa", "bbb"])); //this指向obj对象 //console.log(arr);  输出  ["aaa", "bbb"]
// 实例二
//用 apply 将数组各项添加到另一个数组
var array = ["a", "b"];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]

func.call(thisArg, arg1, arg2, …)

func.call(thisArg,[argsArray])

thisArg: 必填项,传入一个需要 this 指向的对象,否则 this 指向 Window

arg1,arg2,… : 选填项,可以传入多个参数

//实例一
let obj = {
  name: "张三",
  age: 18,
  sex: "man",
};
function isCall(obj, obj1) {
  console.log(obj); //{name:'aaa'}
  console.log(obj1); //{name:'bbb'}
  return this;
}
console.log("call", isCall.call(obj, { name: "aaa" }, { name: "bbb" })); //this指向obj

func.bind()

func.bind(thisAr,[, arg1[, arg2[, …]]])

thisArg:必填项,传入一个需要 this 指向的对象,否则 this 指向 Window

argsArray: 选填项,传入个数组

let obj = {
  name: "张三",
  age: 18,
  sex: "man",
};
function isBild(aa) {
  console.log(aa);
  return this;
}
// 在使用bind()运行时需要在结尾加上()  例如 isBild.bind()()
console.log(isBild.bind()()); //this指向Window   //输出undefined
console.log(isBild.bind(obj, "aaa")()); //this指向obj  //输出aaa
let arr = ["aa", "bb", "cc"];
console.log(isBild.bind(obj, arr)()); //this指向obj  //输出["aa",'bb','cc']

apply(),bind(),call()的相同点和不同点

相同点

  • 这三方法都可以改变 this 指向

不同点

  • bind()方法运行时不会自动调用方法,而其他两个可以
  • apply()方法的第二个参数只能传数组,call()方法可以传多个参数
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值