【发布时间】:2013-04-08 14:27:52
【问题描述】:
我是 JavaScript 新手(本周开始学习)。我已经完成了 CodeCademy 课程(实际上只是 Objects 1 && 2 部分,其余部分很无聊)。我以为我学习了构造函数的原型继承,但我已经开始观看 Douglas Crockford: Advanced JavaScript
就在视频的开头,他提到了 2 种继承类型,而我已经意识到,我以为我知道的一切,我都不知道。所以我开始使用 Chrome JavaScript 控制台并尝试使用这两种继承模型来做一些事情。
//create constructor
function MyParent(){
this.name = "joe";
this.sayHi = function(){
console.log(this.name);
}
}
//create child object and inherit from parent
var myChild1 = new MyParent();
myChild1.name
"joe"
myChild1.sayHi()
joe
//add method to MyParent, so it can be accessed from myChild1
MyParent.prototype.sayBye = function(){ console.log("bye");}
myChild1.sayBye()
bye
//create another constructor
function MyParent2(){
this.sayHi = function(){
console.log("hi");
}
}
//make it inherit from MyParent, overwriting sayHi if object is instance of MyParent2
MyParent2.prototype = new MyParent();
//overwrote sayHi
var myChild11 = new MyParent2();
myChild11.sayHi();
hi
//still same as MyParent as its not overwriten in MyParent2
myChild11.name
"joe"
比我尝试使用 Object.create 做同样的事情:
//create an object
var myParent = {
name : "joe",
sayHi : function(){
console.log(this.name)
}
};
//it works
myParent.sayHi()
joe
//create child object
var myChild = Object.create(myParent);
myChild.sayHi()
joe
//add bye method to myChild
myChild.sayBye = function(){ console.log("bye"); }
myChild.sayBye();
bye
//add bye method to myParent - does not overwrite child's bye
myParent.sayBye = function(){ console.log("bye2"); }
//however adding sayBye2 to parent, becomes available on already created child
myParent.sayBye2 = function(){ console.log("bye2"); }
myChild.sayBye2();
bye2
//but its the parent property
myChild.hasOwnProperty("sayBye2")
false
//could make million objects inherit from each other vertically or horizontally
var myChild2 = Object.create(myChild);
myChild2.name
"joe"
到目前为止,就第一印象而言,我确实喜欢这两个模型,也许我更喜欢后者。它似乎更具表现力和强大。
我在vs. 主题上进行了一些搜索,但找不到可以解释每种方法的优缺点的好文章(除了后者仅由较新的浏览器支持,但有一个简单的解决方法)。我发现的其他帖子只是 tl: dr;有点无聊。
所以我的问题是,我应该使用哪种类型的继承。是否有任何相关的特权?两者都有什么主要的缺点吗?可以混用吗? (例如。我知道你可以将对象作为参数传递给new Constructor()))
谢谢
编辑: 如果浏览器不支持它,看看创建 Object.create() 替代方案的技巧,我意识到黑客是多么简单。它基本上是创建一个空的构造函数,将父对象分配为其原型,并将构建的构造函数作为新对象返回。多么整洁的黑客!
if(typeof Object.create !== "function") { Object.create = function (o) { function F() {}; F.prototype = o; return new F(); }; }
但是这意味着什么?有什么需要注意的问题吗?
【问题讨论】:
标签: javascript