// プロトタイプの継承
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())
2 番目が古典的で、1 番目が原型であることを誰か教えてください。私はhttp://www.objectplayground.com/を見ていましたが、私たちが使用する場合Object.create()
とオブジェクトの場合の両方で完全に混乱していprototype
ます。