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