我一直在尝试许多方法来实现这一目标,但没有成功。有谁能够帮我?

基础对象:

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,它可以返回“ recording”的值(来自Recorder)。有什么建议?我尝试了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'recording',这可能是因为我没有尝试正确访问它。有什么建议?

最佳答案

您可以通过在要创建的对象上调用父构造函数来处理简单继承,因此可以执行以下操作:

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/

10-11 21:08