JavaScript - 对象方法



JavaScript 对象方法

JavaScript 对象方法是包含函数定义的对象属性。对象是属性的集合,属性是名称(或键)和值之间的关联。属性的值可以是一个函数;在这种情况下,该属性被称为方法。

您可以直接将方法添加到对象,也可以将其作为属性值添加。该方法还可以接受参数并返回值。对象方法是向对象添加功能的强大方法。它们允许您封装代码并使其可重用。

语法

按照以下语法将方法添加到对象。

const obj = {
	sum: function () {
		// Method body
	}
}
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.tutorialspoint.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.tutorialspoint.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>

输出

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
广告
© . All rights reserved.