【问题标题】:How to reference base variable with inheritance如何通过继承引用基变量
【发布时间】:2014-07-02 15:22:00
【问题描述】:

我一直在尝试很多方法来实现这一点,但都没有成功。有人可以帮帮我吗?

基础对象:

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' 未定义,可能是因为我没有尝试正确访问它。有什么建议吗?

【问题讨论】:

标签: javascript jquery inheritance prototypal-inheritance


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多