Javascript 阐述This对象的理解?

在 JavaScript 中,this 关键字是一个特殊的对象,它在函数被调用时自动定义。this 的值取决于函数调用的上下文,也就是函数是如何被调用的。以下是一些常见使用情况:

  1. 在全局作用域或函数外部调用 this,或者在非严格模式下的函数内部调用 this,它将指向全局对象,在浏览器中,这通常是 window 对象。
console.log(this); // 输出:Window {...}
  1. 在函数内部以严格模式(use strict)调用 this,它将返回 undefined
function strictFunction() {
    'use strict';
    console.log(this);
}
strictFunction(); // 输出:undefined
  1. 在对象的方法中调用 this,它将指向该方法所属的对象。
let obj = {
    name: 'Test Object',
    display: function() {
        console.log(this.name);
    }
};
obj.display(); // 输出:'Test Object'
  1. 在构造函数中调用 this,它将指向新创建的对象。
function Person(name) {
    this.name = name;
}
let person = new Person('John Doe');
console.log(person.name); // 输出:'John Doe'
  1. 当使用 callapplybind 方法调用函数时,this 将指向我们传递给这些方法的第一个参数。
function showName() {
    console.log(this.name);
}
let obj1 = {name: 'John'};
let obj2 = {name: 'Jane'};

showName.call(obj1); // 输出:'John'
showName.call(obj2); // 输出:'Jane'

总的来说,this 的值并不是在编写时确定的,而是在运行时确定的,取决于函数的调用方式。这也是 this 在 JavaScript 中的一个独特和重要的特性。

发表评论

后才能评论