this 的指向?
this
的指向一般指向函数调用者,也有可能指向全局
,严格模式下指向undefinded
- 箭头函数
this
指向外层函数的this
说出下面的代码的输出
javascript
function foo() {
console.log(this.a);
var a = 2;
return this.a; // undefined
}
foo(); // undefined
javascript
const obj = {
a: 1,
foo() {
console.log(this.a);
},
};
obj.foo(); // 1
javascript
const obj = {
a: 1,
foo: () => {
console.log(this.a);
},
};
改变 this 指向的方法?
call
apply
bind
它们区别?
call
可以改变 this 指向,并且可以传参数 并执行函数apply
可以改变 this 指向,并且可以传参数,但是参数是数组bind
可以改变 this 指向,并且可以传参数,但是不会执行函数,不会执行函数,而是返回一个函数,需要手动调用