// 原型继承
var AnswerPrototype = {
constructor: function(value){
this._val = value;
},
get: function(){
return this._val;
}
}
var lifeAnswer = Object.create(AnswerPrototype);
lifeAnswer.constructor(100);
alert(lifeAnswer.get());
var desertAnswer = Object.create(AnswerPrototype);
desertAnswer.constructor(200);
alert(desertAnswer.get());
var firmAnswerProtoype = Object.create(AnswerPrototype);
firmAnswerProtoype.get = function(){
return AnswerPrototype.get.call(this);
}
var luckyAnswer = Object.create(firmAnswerProtoype);
luckyAnswer.constructor(1);
alert(luckyAnswer.get());
var magicAnswer = Object.create(firmAnswerProtoype);
magicAnswer.constructor(2);
alert(magicAnswer.get());
// 经典继承
function Answer(value){
this._val = value;
}
Answer.prototype.get = function(){
return this._val;
}
var lifeAnswer = new Answer(100);
alert(lifeAnswer.get());
var desertAnswer = new Answer(200);
alert(desertAnswer.get());
function firmAnswer(value){
return Answer.call(this,value);
}
firmAnswer.prototype = Object.create(Answer);
firmAnswer.prototype.constructor = firmAnswer;
firmAnswer.prototype.get = function(){
return Answer.prototype.get.call(this);
}
var luckyAnswer = new firmAnswer(20);
alert(luckyAnswer.get())
谁能告诉我第二个是经典的,第一个是原型的。我在看http://www.objectplayground.com/Object.create()
并且在我们使用和prototype
对象的情况下我都感到非常困惑。