JS--改变函数中this的指向三种方法

function test(x, y){
	console.log(x, y, this)
}
test()
// 直接调用test,很显然this指向window

let p = new test(3, 5);
//new 实例化后:this指向构造函数 3, 5, test(){} 

// 基础:
//一:bind
test.bind(test, 33 , 22)();
//改变this,bind,生成一个新的函数,且this指向为第一个参数,其余参数为新函数的参数
//bind仅改变this,不会直接调用

//二:call
test.call(test, 30, 55);
//第一个参数为this指向的并直接调用函数: 30, 55, test(){}

//三:apply
//该方法的语法和作用与 call() 方法类似,只有一个区别,就是 apply() 方法接受的是一个包含多个参数的数组, 而 call() 方法接受的是一个参数列表
test.apply(test, [33, 55]): 30, 55, test(){}

// 稍复杂:
function Product(name, price) {
  this.name = name;
  this.price = price;
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

console.log(new Food('cheese', 5).name);
//知道是什么吗?猜一下答案?这里call相当于继承了Product中的方法,以前看这里的时候
//不太明白,前段时间自学了一下java,现在看这里,恍然大明白。。。几乎一样呀!
//在Food内部写Product.call(this, name, price),最后的结果相当于
function Food(name, price) {
  this.name = name;
  this.price = price;
  this.category = 'food';
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值