1.this是什么?
谁调用当前函数或者方法, this就是谁
2.这三个方法的作用是什么?
这三个方法都是用于修改
函数或者方法
中的this
的
2.1.bind方法作用
修改函数或者方法中的this为指定的对象, 并且会
返回
一个修改之后的新函数
注意点: bind方法除了可以修改this以外, 还可以传递参数, 只不过参数必须写在this对象的后面
function test(a, b) {
console.log(a, b);
console.log(this);
}
test(10, 20);
window.test();
let fn = test.bind(obj, 10, 20);
fn();
function Person() {
this.name = "lnj";
this.say = function () {
console.log(this);
}
}
let p = new Person();
p.say();
// bind
let fn = p.say.bind(obj);
fn()
2.2.call方法作用
修改函数或者方法中的this为指定的对象, 并且会
立即调用修改之后的函数
function test(a, b) {
console.log(a, b);
console.log(this);
}
test.call(obj, 10, 20);
function Person() {
this.name = "lnj";
this.say = function () {
console.log(this);
}
}
let p = new Person();
p.say();
// call
p.say.call(obj);
注意点: call方法除了可以修改this以外, 还可以传递参数, 只不过参数必须写在this对象的后面
2.3.apply方法作用
修改函数或者方法中的this为指定的对象, 并且会
立即调用修改之后的函数
注意点: apply方法除了可以修改this以外, 还可以传递参数, 只不过参数必须通过数组的方式传递
function test(a, b) {
console.log(a, b);
console.log(this);
}
test.call(obj,[10, 20]);
function Person() {
this.name = "lnj";
this.say = function () {
console.log(this);
}
}
let p = new Person();
// p.say();
// apply
p.say.apply(obj);