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';
}
JS--改变函数中this的指向三种方法
最新推荐文章于 2023-02-20 15:34:43 发布