簡體   English   中英

訪問范圍外的匿名函數中的“私有”成員

[英]Accessing “private” members within an anonymous function outside scope

基本上我要做的是為匿名函數提供對“私有”函數/變量的訪問。 我需要一些關於我實現這一目標的方法的意見,以及可能更好地替代這些方法。 小提琴

請觀察以下代碼段。

function Something()
{
    /*private*/ var _someVariable = 1;

    /*private*/ function _someFunction() {
        alert('_someFunction');
    }

    /*public*/this.SomeDelegate1 = function(codeblock) {
        var members = $.extend({ 
            _someVariable : _someVariable,
            _someFunction:_someFunction 
        }, this);           
        codeblock.apply(members);
    }

    /*public*/this.SomeDelegate2 = function(codeblock) {
        var caller = eval('(' + codeblock + ')');
        caller.apply(this);
    }           

}

在SomeDelegate1中,我將我的私有成員轉換為實例成員,並將其作為上下文傳遞給匿名函數,如下所示。

var someInstance = new Something();
someInstance.SomeDelegate1(
    function() {
        this._someFunction();
        alert(this._someVariable);
    }
);

我喜歡這樣一個事實:人們可以指定你想要公開哪些成員,但它可能會變得非常笨重,例如當你需要更新“私有”變量時。

我顯然可以將所有成員都寫為實例成員,但我寧願讓它們保持“私有”,只允許在回調函數范圍內進行訪問。

在SomeDelegate2中,我使用了一個eval(是的,我知道與此相關的所有邪惡和巫術)。

var someInstance = new Something();
someInstance.SomeDelegate2(
    function() {
        _someFunction();
        alert(_someVariable);
    }
);

由於我將代碼注入函數,因此“私有”作用域成員可自動使用,因此我不需要對成員進行任何復制等,也不需要做很多工作。

這種方法存在根本問題嗎?

你有更好的替代品/方法來實現這一目標嗎?

正如我在評論中所說,我會將所有內容公開,並使用下划線為“私有”屬性名稱加上前綴。 這就是我重構代碼的方式:

 function defclass(prototype) { var constructor = prototype.constructor; constructor.prototype = prototype; return constructor; } var Something = defclass({ constructor: function () { this._someVariable = 1; }, _someFunction: function () { alert("someFunction"); }, someDelegate1: function (f) { f.apply(this); }, someDelegate2: function (f) { f.call(this, this._someVariable, this._someFunction); } }); var someInstance = new Something; someInstance.someDelegate1(function () { this._someFunction(); alert(this._someVariable); }); someInstance.someDelegate2(function (someVariable, someFunction) { someFunction(); alert(someVariable); }); 

然而,這只是我的意見。 我真的沒有看到私有變量的意義。 即使有人對你的私人變量感到困惑,這也是他們的問題而不是你的問題。 它會打破他們的代碼而不是你的代碼。

暫無
暫無

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

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