给 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