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
廣告