如何在 JavaScript 中调用对象内部的函数
我们可以通过将函数声明为对象的属性并调用它来调用对象内部的函数,例如 obj.sum(2, 2)
。 一个对象的属性可以指向一个函数,就像它可以指向一个字符串、数字或其他值一样。
const obj = {
sum(a, b) {
return a + b;
},
};
console.log(obj.sum(10, 10)); // 👉️ 20
console.log(obj.sum(10, 20)); // 👉️ 30
我们在一个对象上声明了一个 sum
属性。 该属性指向一个函数。
const obj = {
sum(a, b) {
return a + b;
},
};
console.log(typeof obj.sum); // 👉️ "function"
我们可以使用点访问对象的属性。 或括号
[]
符号来调用函数。
我们使用简写属性来定义对象中的函数。
在阅读旧代码时,我们可能会看到使用了以下更冗长和过时的方法。
const obj = {
sum: function (a, b) {
return a + b;
},
};
console.log(obj.sum(10, 10)); // 👉️ 20
console.log(obj.sum(10, 20)); // 👉️ 30
第一种方法更简洁,更易于阅读。
我们可以使用 this
关键字在函数内部访问对象的属性。
const obj = {
num: 100,
sum(a, b) {
return a + b + this.num;
},
};
console.log(obj.sum(1, 1)); // 👉️ 102
在此特定上下文中,this
关键字指的是对象。
我们还可以在对象声明后向其添加一个函数。
const obj = {
num: 100,
};
obj.sum = function (a, b) {
return a + b + this.num;
};
console.log(obj.sum(10, 10)); // 👉️ 120
请注意
,我们使用function
关键字来定义函数。 如果我们使用箭头函数,则this
关键字的值将不会被正确绑定并且会指向封闭范围(而不是对象)。
const obj = {
num: 100,
};
obj.sum = (a, b) => {
console.log(this); // 👉️ {}
return a + b + this.num;
};
console.log(obj.sum(10, 10)); // 👉️ NaN
箭头函数不像命名函数那样有自己的 this
关键字。 相反,箭头函数使用封闭范围的 this
上下文。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。