簡體   English   中英

為什么結果是全球名稱,這是由“這個”引起的?

[英]why the result is global name , is this caused by “this”?

global.name ="global";

var object2 = {
    name:"My Object 2",
    doSomething:function(){
        return function(){
            return this.name;
        };
    }
};

console.log(object2.doSomething()());

為什么結果是“全局”,而不是“我的對象2”?

.doSomething()函數返回的函數在沒有任何上下文的情況下被調用,因此this的值將是全局上下文。

根據您的需要,您可以以不同的方式提供上下文。 例如,你可以讓doSomething()總是返回一個綁定到其調用所涉及對象的函數:

doSomething:function(){
    return function(){
        return this.name;
    }.bind(this);
}

您還可以在調用時明確提供上下文:

console.log(object2.doSomething().call(object2));

這就是為什么,在第一次調用嵌套在console.log()調用之前,傳遞的參數可能被認為是這樣的

console.log(function(){return function(){ return this.name;})

// Note how that the console.log method has not reached yet the (this) reference, it's still like a black box for it

並且在第一次調用執行后,它看起來像這樣:

console.log(function(){ return this.name;})

現在,在執行時, console.log()方法將解析this值,並且由於它在全局上下文中執行,因此它將獲取存儲在全局對象上的變量name的值。

因此,這里重要的是調用函數的位置,而不是它的定義方式和位置。

注意 :您的代碼示例不是100%正確,因為您在第一行中以隱式方式定義了一個global對象,並將名為name的屬性設置為"global"值。

this在這方面是指創建對象的關閉-在這種情況下,它是全球性的。

如果你想讓它在自己的閉包中工作,你可以這樣做:

global.name ="global";

function MyObject(name) {
    this.name = name;
    return {
        doSomething: function(){
            return this.name;
        }
    }
}

var object2 = new MyObject("My Object 2");

console.log(object2.doSomething());

暫無
暫無

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

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