我试图理解 JavaScript 的原型性质,并且我试图在不使用类之类的构造函数的情况下创建对象继承。
如果它们都是三个对象文字,我如何将原型链从 Animals 附加到 Cat 和 Dog?
此外,有没有办法执行 Object.create 并以文字形式添加更多属性(如 myCat)。
我添加了下面的代码并粘贴 bin http://jsbin.com/eqigox/edit#javascript
var Animal = {
name : null,
hairColor : null,
legs : 4,
getName : function() {
return this.name;
},
getColor : function() {
console.log("The hair color is " + this.hairColor);
}
};
/* Somehow Dog extends Animal */
var Dog = {
bark : function() {
console.log("Woof! My name is ");
}
};
/* Somehow Cat Extends Animal */
var Cat = {
getName : function() {
return this.name;
},
meow : function() {
console.log("Meow! My name is " + this.name);
}
};
/* myDog extends Dog */
var myDog = Object.create(Dog);
/* Adding in with dot notation */
myDog.name = "Remi";
myDog.hairColor = "Brown";
myDog.fetch = function() {
console.log("He runs and brings back it back");
};
/* This would be nice to add properties in litteral form */
var myCat = Object.create(Cat, {
name : "Fluffy",
hairColor : "white",
legs : 3, //bad accident!
chaseBall : function(){
console.log("It chases a ball");
}
});
myDog.getColor();