📅  最后修改于: 2023-12-03 14:39:15.698000             🧑  作者: Mango
在 JavaScript 中,"this" 是一个关键字,表示当前函数执行的上下文,即当前函数所属的对象。
const obj = {
name: 'John',
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
obj.greet(); // 输出:Hello, my name is John
function Person(name, age) {
this.name = name;
this.age = age;
}
const person1 = new Person('John', 30);
const person2 = new Person('Jane', 25);
console.log(person1); // 输出:{name: "John", age: 30}
console.log(person2); // 输出:{name: "Jane", age: 25}
const obj = {
name: 'John',
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
const greetFunction = obj.greet;
greetFunction(); // 输出:Hello, my name is undefined
// 若不使用 "this" 关键字,得到的结果为:
// 输出:Hello, my name is undefined
// 在使用 "this" 关键字时,得到的结果为:
// 输出:Hello, my name is John
console.log(this === window); // 输出:true
function foo() {
console.log(this === window);
}
foo(); // 输出:true
const obj = {
name: 'John',
greet: function() {
console.log(this);
}
};
obj.greet(); // 输出:{name: "John", greet: ƒ}
function Person(name, age) {
this.name = name;
this.age = age;
console.log(this);
}
const person1 = new Person('John', 30);
const person2 = new Person('Jane', 25);
console.log(person1); // 输出:{name: "John", age: 30}
console.log(person2); // 输出:{name: "Jane", age: 25}
const obj1 = {
name: 'John',
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
const obj2 = {
name: 'Jane'
};
obj1.greet.call(obj2); // 输出:Hello, my name is Jane
在 JavaScript 中,"this" 是一个很重要的关键字,它可以帮助我们轻松地处理对象、方法和构造函数的相关操作,并且可以使代码更加可读性和可维护性。