this 指向
在JavaScript中, this 关键字用于引用当前执行代码的上下文。 this 的值通常是在函数被调用时确定的,它的指向可以根据函数的调用方式而变化。本文将介绍 this 指向的一些常见情况,包括普通函数和箭头函数,并给出相应的示例。
在普通函数中, this 的值取决于函数的调用方式。下面为示例:
在全局上下文中,即在函数外部,this指向全局对象window。
console.log(this);
当函数作为对象的方法被调用时,this指向调用该方法的对象。
var person = {
name: 'John',
greet: function() {
console.log('Hello, ' + this.name);
}
};
person.greet();
当函数用作构造函数时(使用new关键字),this指向正在创建的新对象。
function Person(name) {
this.name = name
}
var person = new Person('John')
console.log(person.name)
-
使用 call 或 apply 改变 this 指向
通过使用 call 或 apply 方法,可以显式地改变函数的 this 指向。 this 将被设置为传递给 call 或 apply 方法的第一个参数。
function greet() {
console.log('Hello, ' + this.name);
}
var person = { name: 'John' };
greet.call(person);
箭头函数与普通函数的主要区别在于 this 的指向。箭头函数没有自己的 this 绑定,它继承了父级作用域中的 this 值。
var person = {
name: 'John',
greet: function() {
var innerFunc = () => {
console.log('Hello, ' + this.name);
};
innerFunc();
}
};
person.greet();
-
总结
- 在全局上下文中,this指向全局对象window。
- 当函数作为对象的方法被调用时,this指向调用该方法的对象。
- 当函数用作构造函数时,this指向正在创建的新对象。
- 使用call或apply方法可以显式地改变函数的this指向。
- 箭头函数没有自己的this绑定,它继承了父级作用域中的this值。
- 以上是关于JavaScript中this指向的一些常见情况和示例