if(typeof Object.create!='function'){
Object.create = function(o){
var F = function(){};
F.prototype = o;
return new F();
}
}
var o = Object.create(a)
/**********/
function inheritPrototype(subType,superType){
// 两个参数:子类型构造函数和超类型构造函数
var prototype = object(superType.prototype);
// 创建超类型原型的副本
prototype.constructor = subType;
// 为副本添加constructor属性,弥补重写原型失去默认constructor属性
subType.prototype = prototype;
// 创建的新对象赋值给子类型的原型
}
/*********/
function extend(base, sub) {
var origProto = sub.prototype;
sub.prototype = Object.create(base.prototype);
for (var key in origProto) {
sub.prototype[key] = origProto[key];
}
// Remember the constructor property was set wrong, let's fix it
sub.prototype.constructor = sub;
// In ECMAScript5+ (all modern browsers), you can make the constructor property
// non-enumerable if you define it like this instead
Object.defineProperty(sub.prototype, 'constructor', {
enumerable: false,
value: sub
});
}
// Let's try this
function Animal(name) {
this.name = name;
}
Animal.prototype = {
sayMyName: function() {
console.log(this.getWordsToSay() + " " + this.name);
},
getWordsToSay: function() {
// Abstract
}
}
function Dog(name) {
// Call the parent's constructor
Animal.call(this, name);
}
Dog.prototype = {
getWordsToSay: function(){
return "Ruff Ruff";
}
}
// Setup the prototype chain the right way
extend(Animal, Dog);
// Here is where the Dog (and Animal) constructors are called
var dog = new Dog("Lassie");
dog.sayMyName(); // Outputs Ruff Ruff Lassie
console.log(dog instanceof Animal); // true
console.log(dog.constructor); // Dog