【发布时间】:2017-06-12 11:44:31
【问题描述】:
我正在学习 Javascript 中的面向对象编程。 我从这里http://www.objectplayground.com/ 得到了这个视频课程,我对经典方法的原型方法了解很多。
在观看课程时,我被下面展示的经典方法处理子类的示例打断了:
//superclass
function Answer(value){
this._val = value;
}
//define prototype property 'get' for the superclass
Answer.prototype.get = function fn1(){
return this._val;
}
//subclass
function FirmAnswer(value){
Answer.call(this,value);
}
FirmAnswer.prototype = Object.create(Answer.prototype);
FirmAnswer.prototype.constructor = FirmAnswer;
//define prototype property 'get' for subclass
FirmAnswer.prototype.get = function fn2(){
return Answer.prototype.get.call(this);
}
var luckAnswer = new FirmAnswer(7);
luckAnswer.get(); //7
问题:
根据我对call函数的理解,它将this设置为当前上下文,例如来自FirmAnswer函数的Answer.call(this,value)这一行,所以Answer中的_val将设置为FirmAnswer 而不是Answer(如果我错了,请纠正我)。
因此,如果上述分析正确,我会感到困惑,为什么FirmAnswer.prototype 的get 属性返回Answer.prototype.get.call(this) 而不仅仅是Answer.prototype.get(),因为this 已经设置为FirmAnswer 什么时候打电话给new FirmAsnwer(7)?
请给我一些启发,因为我现在很困惑。我很确定我很了解原型方法,但经典方法让我很困惑。
提前感谢您!
【问题讨论】:
标签: javascript prototype-programming prototype-chain prototype-pattern