05.定义构造函数

说明

constructor 构造函数是创建新对象的函数。它们定义新对象的属性和行为。将它们视为创建新对象的蓝图。

以下是 constructor 构造函数的示例:

function Bird() {
   this.name = "Albert";
   this.color = "blue";
   this.numLegs = 2;
}

这个 constructor 定义了具有 namecolor 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;
}
发布了56 篇原创文章 · 获赞 1 · 访问量 824

猜你喜欢

转载自blog.csdn.net/weixin_44790207/article/details/104976714