这篇文章中,我们来研究一下this 的指向问题,在 JavaScript 中this 的指向取决于一个方法是如何被调用的,我们可以根据下面几项来判断 this 到底指向什么。
- 默认情况,this 在 NodeJS 环境里指向 global对象,而在浏览器里,this 指向 window 对象
function foo () {
console.log("Simple function call");
console.log(this === window);
}
foo(); //prints true on console
console.log(this === window) //Prints true on console.
(function(){
console.log("Anonymous function invocation");
console.log(this === window);
})();
// Prints true on console
- 当一个方法被作为一个对象的一个参数调用时,this 指向此对象
function foo () {
'use strict';
console.log("Simple function call")
console.log(this === window);
}
let user = {
count: 10,
foo: foo,
foo1: function() {
console.log(this === window);
}
}
user.foo() // Prints false because now “this” refers to user object instead of global object.
let fun1 = user.foo1;
fun1() // Prints true as this method is invoked as a simple function.
- 当一个方法使用 new 操作符调用,此 this 指向这个新创建的实例
function Person(fn, ln) {
this.first_name = fn;
this.last_name = ln;
this.displayName = function() {
console.log(`Name: ${this.first_name} ${this.last_name}`);
}
}
let person = new Person("John", "Reed");
person.displayName(); // Prints Name: John Reed
let person2 = new Person("Paul", "Adams");
person2.displayName(); // Prints Name: Paul Adams
- 当方法用 call 或者 apply 被调用时,this 指向 call 或 apply 函数的第一个参数
function Person(fn, ln) {
this.first_name = fn;
this.last_name = ln;
this.displayName = function() {
console.log(`Name: ${this.first_name} ${this.last_name}`);
}
}
let person = new Person("John", "Reed");
person.displayName(); // Prints Name: John Reed
let person2 = new Person("Paul", "Adams");
person2.displayName(); // Prints Name: Paul Adams
person.displayName.call(person2); // Here we are setting value of this to be person2 object
对学习抱有热情的开发小伙伴欢迎加入 qq群685421881,更欢迎热爱编程的妹子进入,让我们一起学习 并进步吧!
网友评论