06.使用构造函数创建对象

说明

以下是来自上一个挑战的 Bird 的构造函数:

function Bird() {
   this.name = "Albert";
   this.color = "blue";
   this.numLegs = 2;
   //"this"在构造函数内总是引用正在创建的对象
}

let  blueBird = new Bird();

请注意,调用构造函数时使用 new 运算符,既是告诉 JavaScript 创建一个叫做 blueBird Bird 的新实例。没有 new 运算符 ,构造函数中的 this 不会指向新创建的对象,从而产生意料之外的结果。

现在 blueBird 具有在 Bird 构造函数内定义的所有属性:

blueBird.name; // => Albert

blueBird.color; // => blue

blueBird.numLegs; // => 2

就像任何其他对象一样,它的属性可以被访问和修改:

blueBird.name = 'Elvira';

blueBird.name; // => Elvira


练习

使用上节课中的 Dog 构造函数创建一个新的 Dog 实例,将变量 hound 指定给它。

hound 应该使用 Dog 的构造函数创建。

你的代码应该使用 new 运算符创建一个 Dog 的实例。

答案

方法 描述
new 创建一个用户定义的对象类型实例或具有构造函数的内置对象实例
let 声明一个块级作用域的本地变量,并且可选的将其初始化为一个值。
function Dog() {
this.name = "Rupert";
this.color = "brown";
this.numLegs = 4;
}
// Add your code below this line
let hound=new Dog();
发布了56 篇原创文章 · 获赞 1 · 访问量 823

猜你喜欢

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