freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../object-oriented-programming/use-a-constructor-to-create...

2.2 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7dad367417b2b2512b78 Use a Constructor to Create Objects 1 使用构造函数创建对象

Description

这是上一次挑战中的Bird构造函数:
function Bird{
this.name =“阿尔伯特”;
this.color =“blue”;
this.numLegs = 2;
//构造函数中的“this”始终引用正在创建的对象
}

让blueBird = new Bird;
请注意,在调用构造函数时使用new运算符。这告诉JavaScript创建一个名为blueBirdBirdinstance 。如果没有new运营商, this在构造函数中不会指向新创建的对象,给人意想不到的效果。现在, blueBird具有在Bird构造函数中定义的所有属性:
blueBird.name; // =>艾伯特
blueBird.color; // =>蓝色
blueBird.numLegs; // => 2
就像任何其他对象一样,可以访问和修改其属性:
blueBird.name ='Elvira';
blueBird.name; // =>埃尔维拉

Instructions

使用上一课中的Dog构造函数创建Dog的新实例,将其分配给变量hound

Tests

tests:
  - text: 应该使用<code>Dog</code>构造函数创建<code>hound</code> 。
    testString: 'assert(hound instanceof Dog, "<code>hound</code> should be created using the <code>Dog</code> constructor.");'
  - text: 您的代码应该使用<code>new</code>运算符来创建<code>Dog</code>的<code>instance</code> 。
    testString: 'assert(code.match(/new/g), "Your code should use the <code>new</code> operator to create an <code>instance</code> of <code>Dog</code>.");'

Challenge Seed

function Dog() {
  this.name = "Rupert";
  this.color = "brown";
  this.numLegs = 4;
}
// Add your code below this line

Solution

// solution required