簡體   English   中英

將此綁定到嵌套文字對象中

[英]Bind this in nested literal object

假設我有這段代碼

(function() {

    function Foo(arg) {
        this.name = arg;
    }

    Foo.prototype = {
        bar: {
            baz: function() {
                alert(this.name); // Undefined...
            }
        }
    }

    var foo = function(arg) {
        return new Foo(arg);
    };


    window.foo = foo;

    return foo;
}());

foo("Anything").bar.baz();

當我從外部調用對象時,如何在我的函數“ baz”中使“ this”指向對象Foo而不使用綁定或應用?

FWIW,我強烈建議不要建立這樣的嵌套結構,或者至少不要在原型上建立嵌套結構,因為bar對象在所有實例之間都是共享的,這打開了許多串擾式bug的大門。 相反,我會在構造函數中創建bar

當我從外部調用對象時,如何在我的函數“ baz”中使“ this”指向對象Foo而不使用綁定或應用?

您可能對bindapply / call感到有些困惑。 調用函數時,您將不會使用bind ,而在創建函數時,您將不使用bind 除非您使用bind (或等效的東西),否則您bind無法執行您想要說的話,因為缺少bind (或類似的東西), this this.bar.baz()函數的調用方式,因此this.bar.baz()this設為通話中的this.bar

這是在構造函數中構建bar的方法,並使用bind使baz使用正確的this

function Foo(arg) {
    this.name = arg;
    this.bar = {
        baz: function() {
            alert(this.name);
        }.bind(this)            // <== Note
    };
}

例:

 function Foo(arg) { this.name = arg; this.bar = { baz: function() { snippet.log(this.name); }.bind(this) // <== Note }; } var f1 = new Foo("f1"); var f2 = new Foo("f2"); f1.bar.baz(); // "f1" f2.bar.baz(); // "f2" 
 <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 


更多關於串擾:天真的事情做的是只有一個行添加到您Foo構造,並保持bar的原型:

this.bar.baz = this.bar.baz.bind(this);

那將是一個非常糟糕的主意 ,因為您將在實例之間發生串擾:

 function Foo(arg) { this.name = arg; this.bar.baz = this.bar.baz.bind(this); // DON'T DO THIS } Foo.prototype = { bar: { baz: function() { snippet.log(this.name); } } }; var f1 = new Foo("f1"); var f2 = new Foo("f2"); f2.bar.baz(); // "f1" -- cross talk! Should be f2 
 <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

在聲明時使用bind來適當地限制它的范圍,例如

function foo() {}.bind(this);

暫無
暫無

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

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