1.全局环境中的this:在全局环境中(非严格模式下),this指向全局对象,也就是window
console.log(this);
2.函数调用中的this:当函数作为普通函数调用时,this指向全局对象(非严格模式下)或者undefined(严格模式下)
function test() {
console.log(this);
}
test();
3.方法调用中的this:当函数作为对象的方法被调用时,this指向调用该方法的对象。
var obj = {
method: function() {
console.log(this);
}
};
obj.method();
4. 构造函数中的this:当函数作为构造函数使用时,this指向新创建的对象。。
function Test() {
this.x = 10;
console.log(this);
}
var obj = new Test();
5. 箭头函数没有自己的this,它的this是继承自外层代码块,它的指向永远指向箭头函数外层的 this
function fn() {
console.log(this);
let fn1 = () => {
console.log(this);
}
fn1();
}
fn();
6. 在js中,call、apply和bind都是可以改变函数运行时this指向的方法,它们都是Function.prototype的方法。
call方法:call方法的第一个参数会被作为被调用函数运行时的this值。后续参数则作为函数的参数传入
function greet() {
console.log(this.name);
}
var person = { name: 'Alice' };
greet.call(person);
apply方法:apply方法的作用和call方法类似,不同之处在于apply接受两个参数,第一个参数作为函数运行时的this值,第二个参数是一个数组,数组中的元素将作为函数的参数传入
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
var person = { name: 'Bob' };
greet.apply(person, ['Hello', '!']);
bind方法:bind方法创建一个新的函数,当这个新函数被调用时,bind的第一个参数将作为它运行时的this,之后的一序列参数将会在传递的实参前传入作为它的参数
function greet() {
console.log(this.name);
}
var person = { name: 'Charlie' };
var boundGreet = greet.bind(person);
boundGreet();