methods中放置this
时间: 2023-10-19 12:05:40 浏览: 36
在 JavaScript 中,this 关键字通常表示当前调用函数的对象。因此,将 this 添加到对象的方法中可以访问对象的属性和方法。
例如:
```
const person = {
name: "John",
age: 30,
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
};
person.greet(); // Hello, my name is John and I am 30 years old.
```
在这个例子中,greet() 方法使用 this 关键字来访问 person 对象的 name 和 age 属性。
另外,将 this 添加到对象的方法中还可以在函数内部使用对象的其他方法。例如:
```
const calculator = {
num1: 0,
num2: 0,
setNums(num1, num2) {
this.num1 = num1;
this.num2 = num2;
},
add() {
return this.num1 + this.num2;
},
subtract() {
return this.num1 - this.num2;
}
};
calculator.setNums(5, 3);
console.log(calculator.add()); // 8
console.log(calculator.subtract()); // 2
```
在这个例子中,setNums() 方法使用 this 关键字来设置 calculator 对象的 num1 和 num2 属性。add() 和 subtract() 方法则在函数内部使用了这些属性来执行计算。