说明
constructor
构造函数是创建新对象的函数。它们定义新对象的属性和行为。将它们视为创建新对象的蓝图。
以下是 constructor
构造函数的示例:
function Bird() {
this.name = "Albert";
this.color = "blue";
this.numLegs = 2;
}
这个 constructor
定义了具有 name
,color
和 numLegs
属性的 Bird
对象,分别为 Albert,blue 和 2 。
constructor
遵循以下约定:
constructor
使用大写的名称定义,以区别于不是构造函数的其他函数。constructor
使用关键词this
来设置它们将要创建的对象的属性。在构造函数中,this
是指它将创建的新对象。constructor
定义属性和行为,而不是像其他函数一样返回一个值。
练习
创建一个构造函数:Dog
。其 name
,color
和 numLegs
属性分别设置为字符串,字符串和数字。
Dog
应该有一个设置为字符串的 name
属性。
Dog
应该有一个设置为字符串的 color
属性
Dog
应该有一个设置为数值的 numLegs
属性
答案
function Dog(){
this.name = "DaHuang";
this.color = "yellow";
this.numLegs = 4;
}