this 指向,函数内外皆有道理
2024-01-18 00:18:37
函数内的 this 指向
在函数内部,this 指向的是函数调用时所属的对象。这种情况下,this 的指向非常明确,主要取决于函数的调用方式。常见情况下,函数有以下几种调用方式:
-
方法调用: 当一个函数作为对象的方法被调用时,this 指向的是该对象本身。例如:
const person = { name: "John Doe", greet: function() { console.log(`Hello, my name is ${this.name}.`); }, }; person.greet(); // 输出: Hello, my name is John Doe.
在这个例子中,当
greet()
方法被调用时,this 指向的是person
对象,因此可以访问到name
属性。 -
构造函数调用: 当一个函数作为构造函数被调用时,this 指向的是新创建的对象。例如:
function Person(name) { this.name = name; } const person1 = new Person("John Doe"); console.log(person1.name); // 输出: John Doe
在这个例子中,当
Person()
函数作为构造函数被调用时,this 指向的是新创建的person1
对象,因此可以访问到name
属性。 -
普通函数调用: 当一个函数作为普通函数被调用时,this 指向的是全局对象,也就是
window
对象。例如:function greet() { console.log(`Hello, my name is ${this.name}.`); } greet(); // 输出: Hello, my name is undefined.
在这个例子中,当
greet()
函数作为普通函数被调用时,this 指向的是全局对象,因此无法访问到name
属性,输出为undefined
。
函数外的 this 指向
在函数外部,this 指向的是全局对象,也就是 window
对象。即使在严格模式下,this 指向的也是全局对象,而不是 undefined
。例如:
console.log(this); // 输出: Window {...}
在浏览器环境中,window
对象代表着浏览器窗口,它包含了大量内置对象和属性,如 document
、location
、navigator
等。因此,在函数外部,我们可以直接访问这些内置对象和属性。
总结
函数内外的 this 指向规则相对明确,可以通过函数的调用方式来判断 this 的指向。在函数内部,this 指向的是函数调用时所属的对象,而在函数外部,this 指向的是全局对象。理解 this 指向的规则对于理解 JavaScript 的运行机制非常重要,特别是对于高级编程技术,如面向对象编程和函数式编程,都需要对 this 指向有深入的了解。