在 JavaScript 中,用 new 关键字来调用的 函数,称为构造函数。
function Obj(attr1, attr2, attr3, ...){
this.attr1 = attr1;
this.attr2 = attr2;
this.attr3 = attr3;
...
this.func = function(){
//todo
}
}
var obj = new Obj(attr1, attr2, attr3, ...);
我们通过 function 关键字,定义了一个构造函数 Obj,接下来,我们需要实例化对象时,直接通过 new 关键字,来实例化该对象即可。
在使用对象字面量创建一系列同一类型的对象时,这些对象可能具有一些相似的特征(属性)和行为(方法),此时会产生很多重复的代码,而使用构造函数就可以实现代码的复用。
使用 JavaScript 构造函数创建对象
<!DOCTYPE html>
<html>
<head>
<title>JavaScript构造函数</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
function Car(make, model, year, owner) {
this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
this.info = function(){
console.log("Car make =", this.make, "model =", this.model, "year =", this.year, "owner =", this.owner);
}
}
var car1 = new Car("Eagle", "Talon TSi", 1993, "rand");
car1.info();
</script>
</head>
</html>
程序运行后,控制台输出如下:
我们使用构造函数的方式,创建了一个 Car 对象,接着,我们调用了 Car 对象的 info 方法。
在 JavaScript 中,用 new 关键字来调用的函数,称为构造函数。