技法65 (◐‿◑) 使用构造函数创建对象
本帖最后由 不二如是 于 2017-8-8 06:37 编辑http://xxx.fishc.com/forum/201705/05/225545py2j222x5z6x55n2.png
按照提示,完成代码,秀秀你的编程能力!
不许看答案,否则打屁屁
分析:
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
I Need U:
使用顶部的Dog构造函数创建一个新的Dog实例,将变量hound指定给它。
function Dog() {
this.name = "Rupert";
this.color = "brown";
this.numLegs = 4;
}
//在下面添加代码
hound应该使用Dog的构造函数创建。
你的代码应该使用new运算符创建一个Dog的实例。
答案:
**** Hidden Message *****
回顾:
技法64 (◐‿◑) 定义构造函数
○面试题索引贴●
如果喜欢,请订阅{:10_303:} :
HTML5 - 庖丁解牛 + JavaScript - 庖丁解牛
1 let hound = new Dog(); dog = new Dog(); 学习学习
em {:5_102:} 学习 回复看看 function Dog() {
this.name = "Rupert";
this.color = "brown";
this.numLegs = 4;
}
//在下面添加代码
let dog = new Dog();
dog.hound = hound; 1
页:
[1]