JavaScript 对象方法
JavaScript 对象方法是包含函数定义的对象属性。对象是属性的集合,而属性是名称(或键)与值之间的关联。属性的值可以是函数;在这种情况下,该属性称为方法。
您可以直接向对象添加方法,也可以将其添加为属性值。该方法还可以获取参数并返回值。对象方法是向对象添加功能的有效方法。它们允许您封装代码并使其可重用。
语法
按照下面的语法向对象添加方法。
const obj = {
sum: function () {
// Method body
}
}
obj.sum();
在上面的语法中,'sum' 是在 'obj' 对象中定义的方法。您可以在访问 object 属性时访问该方法,并添加一对括号以调用该方法。
例在下面的示例中,我们在 'company' 对象中添加了 getInfo() 方法。getInfo() 方法返回包含对象属性的字符串。
在这里,我们使用 'this' 关键字来访问对象内部的对象属性。'this' 关键字表示对象本身。
之后,我们使用该对象作为引用来调用该方法。
<html>
<body>
<p>Company Information</p>
<p id = "output"> </p>
<script>
const company = {
companyName: "Qikepu Com",
companyWebsite: "www.Qikepu.com",
getInfo: function () {
return "Comapny Name: " + this.companyName +"<br>Website: " + this.companyWebsite;
},
}
document.getElementById("output").innerHTML = company.getInfo();
</script>
</body>
</html>
输出
Comapny Name: Qikepu Com
Website: www.Qikepu.com
对象方法速记
ES6 提供了在对象中定义方法的最短方法。
语法
按照下面的语法向对象添加方法。
const Obj = {
sum() {
// Method body
}
}
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>
输出
例
下面的示例定义了 'nums' 对象中的 getSum() 方法。getSum() 方法采用两个参数并返回它们的 sum。
我们在调用方法时将 number 参数传递给该方法。
<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>
输出
更新或向对象添加方法
在 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>
输出
使用内置方法
字符串、数字、布尔值等 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>
输出
Data type of after conversion: string