1

オブジェクトリテラルをと呼ばれるフレームワークメソッドに渡しますsupportP()。このオブジェクトリテラルには_p、そのメンバーがプライベートであることを示すという特別なプロパティがあります。オブジェクトリテラル内のwithから、を介してアクセスできますthis._p。ただし、オブジェクトリテラルを「外部」スコープに渡す場合、コピーしません_p。現在は省略により非公開になっています。パブリックメンバーメソッドから_pにアクセスするために、を使用して元のオブジェクトにバインドし、をbind()介して_pにアクセスできるようにしthisます。

これは機能しますか?他に考慮すべきことはありますか?テストする前にフィードバックが必要でした。

以下は関連するスニペットです。

/*$A.supportP
**
**
**
*/
$A.supportP = function (o, not_singleton) {
    var oo
        key;
    SupportList[o.Name] = {};
    if (not_singleton) {
        // ignore this section
    } else { // *look here - isFunc returns true if a function
        for (key in o) {
            if ((key !== '_p') && (isFunc(o[key])) {
                oo[key] = o[key].bind(o);
            } else if (key !== '_p') {
                oo[key] = o[key];
            } else {
                // private (_p) - anything to do here?
            }
        }
        return oo;
    }
};


/*$A.test
**
**
**
*/
var singleton_object = $A.supportP({
    _p: 'I am private',
    Name: 'test',
    publik_func: function () {
        // this will refer to this object so that it can access _p
        // this._p is accessible here due to binding
    }
}, false);
4

1 に答える 1

1

これは機能しますか?

はい、を介して「プライベート」プロパティにアクセスできますthis._p

他に考慮すべきことはありますか?

オブジェクトのクローンを作成しています。それでも、そのメソッドはそれにアクセスできません。そのプロパティがコピーの変更を反映しない「古い」オブジェクトにバインドされます。これが設計によるものなのか、偶然によるものなのかはわかりません。


厳密なプライバシーのために、ローカル変数でクロージャを使用する必要があります。プロパティを非公開にすることはできません。

var singleton_object = (function() {
    var _p = 'I am private'; // local variable
    return {
        Name: 'test',
        publik_func: function () {
            // this will refer to this object so that it can access the properties
            // _p is accessible here due to closure, but not to anything else
        }
    };
}()); // immediately-executed function expression

フレームワークメソッドに渡される2つの異なるオブジェクト(1つは非表示)を使用する別のソリューション:

function bindPrivates(private, obj) {
    for (var key in obj)
        if (typeof obj[key] == "function")
            obj[key] = obj[key].bind(obj, private);
    return obj;
}

var singleton_object = bindPrivates({
    p: 'I am private'
}, {
    Name: 'test',
    publik_func: function (_) {
        // this will refer to this object so that it can access "public" properties
        // _.p, a "private property" is accessible here due to binding the private 
        //  object to the first argument
    }
});
于 2013-01-23T23:31:11.677 に答える