簡體   English   中英

調用組成的私有類成員的公共實例方法而不使用Java中的直通函數

[英]Calling the public instance methods of a composed private class member without passthrough functions in Javascript

我試圖找到一種避免在類的原型上創建大量傳遞方法的方法。 我有一個ProgressBar類,其中有很多實例方法。 我想創建一個新類(在我的代碼示例中稱為ComposedProgressBar),該類“具有” progressBar實例,並且不繼承自ProgressBar。

為了從客戶端代碼訪問progressBar的實例方法,通常會創建一系列傳遞函數。 如:

ComposedProgressBar.prototype.setWidth = function (width) {
    this.progressBar.setWidth(width);
};

但是,我試圖避免這種情況。

通過將以下內容添加到ComposedProgressBar的構造函數中,我可以訪問progressBar的特權方法:

ProgressBar.call(this);

但是,這不適合我要實現的目標。 我需要訪問已添加到ProgressBar原型的方法。

以下是基於我當前正在使用的示例代碼。 我已經包括了高度設置器和獲取器,只是為了說明使用ProgressBar.call(this)適用於他們。

有可能做我想達到的目標?

function ProgressBar() {
    "use strict";
    this.width = 0;
    this.height = 0;

    this.setHeight = function (height) {
        this.height = height;
    };

    this.getHeight = function () {
        return this.height;
    };
}

ProgressBar.prototype.setWidth = function (width) {
    "use strict";
    this.width = width;
};


ProgressBar.prototype.getWidth = function () {
    "use strict";
    return this.width;
};

function ComposedProgressBar() {
    "use strict";
    this.progressBar = new ProgressBar();
    ProgressBar.call(this);
}


var composedProgressBar = new ComposedProgressBar();

composedProgressBar.setHeight(300);
console.log(composedProgressBar.getHeight());
composedProgressBar.setWidth(300);
console.log(composedProgressBar.getWidth());

我想你可以這樣寫:

for (var methodName in ProgressBar.prototype) {
    if (typeof ProgressBar.prototype[methodName] === 'function'
            && ProgressBar.prototype[methodName]
                   !== ComposedProgressBar.prototype[methodName]) {
        ComposedProgressBar.prototype[methodName] = (function (methodName) {
            return function () {
                return this.progressBar[methodName]
                           .apply(this.progressBar, arguments);
            };
        })(methodName);
    }
}

(自然地,這只會為ProgressBar.prototype中已經存在的方法創建委托:它不會檢測到以后添加的任何方法,並且不支持apply的臨時方法。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM