JavaScript - 对象方法
JavaScript 对象方法
JavaScript 对象方法是包含函数定义的对象属性。对象是属性的集合,而属性是名称(或键)与值之间的关联。属性的值可以是函数;在这种情况下,该属性称为方法。
您可以直接向对象添加方法,也可以将其添加为属性值。该方法还可以接受参数并返回值。对象方法是向对象添加功能的有效方法。它们允许您封装代码并使其可重用。
语法
按照以下语法向对象添加方法。
const obj = {
sum: function () {
// 方法主体
}
}
obj.sum();
在上述语法中,"sum"是定义在"obj"对象内部的方法。您可以像访问对象属性一样访问该方法,并添加一对括号来调用该方法。
示例
在下面的示例中,我们在"company"对象中添加了 getInfo() 方法。getInfo() 方法返回包含对象属性的字符串。
在这里,我们使用"this"关键字来访问对象内部的对象属性。"this"关键字代表对象本身。
之后,我们使用对象作为引用来调用该方法。
<html>
<body>
<p>Company Information</p>
<p id = "output"> </p>
<script>
const company = {
companyName: "Tutorials Point",
companyWebsite: "www.cainiaomax.com",
getInfo: function () {
return "Comapny Name: " + this.companyName +"<br>Website: " + this.companyWebsite;
},
}
document.getElementById("output").innerHTML = company.getInfo();
</script>
</body>
</html>
输出
Company Information Comapny Name: Tutorials Point Website: www.cainiaomax.com
对象方法简写
ES6 提供了在对象中定义方法的最短方法。
语法
请按照以下语法向对象添加方法。
const Obj = {
sum() {
// 方法主体
}
}
Obj.sum();
与上一个方法类似,您可以使用上述语法访问和调用该方法。
示例
在下面的示例中,我们按照上一个示例的方式定义了 getInfo() 方法。
<html>
<body>
<p id = "output"> </p>
<script>
const employee = {
name: "John Doe",
age: 32,
getInfo() {
return "The employee name is " + this.name + " and his age is " + this.age + " Years.";
},
}
document.getElementById("output").innerHTML = employee.getInfo();
</script>
</body>
</html>
输出
The employee name is John Doe and his age is 32 Years.
示例
以下示例在 'nums' 对象中定义了 getSum() 方法。getSum() 方法接受两个参数并返回它们的和。
我们在调用该方法时将数字参数传递给了该方法。
<html>
<body>
<p id = "output">The sum of 2 and 3 is </p>
<script>
const nums = {
getSum(a, b) {
return a + b;
}
}
document.getElementById("output").innerHTML += nums.getSum(2, 3);
</script>
</body>
</html>
输出
The sum of 2 and 3 is 5
更新或添加对象方法
在 JavaScript 中,更新或添加对象方法与更新或添加对象属性相同。您可以使用点或方括号符号来更新或添加对象方法。
示例
以下示例在"nums"对象中定义了 getSum() 方法。
之后,我们在 nums 对象中添加 getMul() 方法。我们通过传递两个参数来调用 getMul() 方法,以获取它们的乘积。
<html>
<body>
<p id = "output">The multiplication of 2 and 3 is </p>
<script>
const nums = {
getSum(a, b) {
return a + b;
}
}
nums.getMul = function (a, b) {
return a * b;
}
document.getElementById("output").innerHTML += nums.getMul(2, 3);
</script>
</body>
</html>
输出
The multiplication of 2 and 3 is 6
使用内置方法
JavaScript 对象(例如字符串、数字、布尔值等)也包含内置方法。您可以通过引用对象来执行这些方法。
示例
在下面的示例中,我们定义了包含数值的"num"变量。之后,我们使用 toString() 方法将数字转换为字符串。
<html>
<body>
<p id = "demo"> </p>
<script>
const output = document.getElementById("demo");
const num = new Number(20);
let str = num.toString();
output.innerHTML += "After converting the number to string: " + str + "<br>";
output.innerHTML += "Data type of after conversion: " + typeof str;
</script>
</body>
</html>
输出
After converting the number to string: 20 Data type of after conversion: string

