給 JavaScript 物件構造器新增一個方法?
在本文中,我們將介紹如何用 JavaScript 中的恰當示例向 JavaScript 物件構造器新增一個方法。
在 JavaScript 中,向物件構造器新增一個方法與向普通物件新增一個方法不同。我們不能像使用普通物件那樣新增方法。要在物件構造器中建立一個方法,必須在物件構造器內新增它。
讓我們透過本文後面的示例更好地理解這個概念。
示例 1
在下面的示例中,方法被新增到構造器內,因此,我們得到一個合法值。
<html>
<body>
<script>
function Business(name, property, age, designation) {
this.Name = name;
this.prop = property;
this.age = age;
this.designation = designation;
this.name = function() {
return this.Name
};
}
var person1 = new Business("Bill gates", "$28.05billion", "71", "Owner");
document.write(person1.name());
</script>
</body>
</html>
執行以上程式碼後,生成以下輸出。
示例 2
這是向 JS 物件構造器新增方法的另一個示例程式。
<!DOCTYPE html>
<html>
<head>
<title>To add a method to a JavaScript Object Constructor.</title>
</head>
<body style="text-align : center">
<h3>Add a method to a JavaScript Object Constructor.</h3>
<p id="method-to-obj-constructor"></p>
<script>
function Car(name, model, year, color) {
this.Name = name;
this.Model = model;
this.Year = year;
this.Color = color;
this.type = 'SUV';
this.description = function() {
return this.Name+" is of "+this.Model+" model and launched in the year "+this.Year+" and is of "+this.type+" type."
}
}
var car1 = new Car("Maruti", "Vitara Brezza", "2016", "Red");
document.getElementById("method-to-obj-constructor").innerHTML = car1.description();
</script>
</body>
</html>
執行以上程式碼後,生成以下輸出。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP