我尝试了很多方法来实现这一目标,但没有成功。有人可以帮助我吗?
基础对象:
var Recorder = function (source) {
this.context = source.context;
var recording = null;
this.start = function () {
recording = true;
}
this.stop = function () {
recording = false;
}
}
派生对象:
var messageRecorder = function () {
this.isRecording = function () {
return this.recording;
}
}
所以我有一个基础对象 Recorder,它有一个 var 'recording'。我想要一个扩展/派生对象 messageRecorder,它可以返回“记录”的值(来自记录器)。有什么建议么?我尝试过 jQuery 扩展,var audioRecorder = $.extend( {}, new Recorder(), new messageRecorder()),但没有成功。我还尝试修改 messageRecording 如下:
var messageRecorder = function () {
Recorder.apple(this, arguments);
this.isRecording = function () {
return this.recording; //declared in Recorder
}
}
并像这样实例化:var audioRecorder = new messageRecorder(source);
在我的两次失败尝试中,当我调用 audioRecorder.start() 时,它工作正常。当我调用 audioRecorder.isRecording() 时,var“录音”未定义,可能是因为我没有尝试正确访问它。有什么建议吗?
最佳答案
您可以通过调用正在创建的对象的父构造函数来处理简单继承,因此您可以执行以下操作:
var Recorder = function (source) {
this.context = source.context;
this.recording = null;
this.start = function () {
this.recording = true;
};
this.stop = function () {
this.recording = false;
};
};
var messageRecorder = function() {
Recorder.apply(this, arguments);
this.isRecording = function() {
return this.recording;
};
};
var src = {
context: 'something'
};
var audioRecorder = new messageRecorder(src);
audioRecorder.start();
console.log("recording? " + audioRecorder.isRecording());
audioRecorder.stop();
console.log("recording? " + audioRecorder.isRecording());
这将为您提供以下输出(正确设置 this.recording
):
recording? true
recording? false
关于javascript - 如何通过继承引用基变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24535031/