簡體   English   中英

函數參數的JavaScript執行上下文

[英]JavaScript execution context of function argument

function Apple(){
    this.name="apple";
}
function Orange(){
    this.name="orange";

    this.apple = new Apple();
    this.apple.onCalled=function(){
        alert(this.name);
    }
}
Orange.prototype.onCalled=function(){
    this.apple.onCalled();
}
var orange = new Orange();
orange.onCalled();

當前代碼顯示為“ apple”。 如何修改“ this.apple.onCalled = function()”行,使其顯示為“橙色”?

即我想將一個函數傳遞給另一個對象,但是當調用該函數時,訪問傳遞該函數的對象的變量,而不是執行該函數的對象的變量。 一個明顯的解決方案是使用全局變量(例如orange.name),但是我正在尋找一種更好的方法,因為有很多對象,並且我不想全局化所有內容。

使用閉包。

function Orange(){
    this.name="orange";

    this.apple = new Apple();
    var that = this;
    this.apple.onCalled=function() {
        alert(that.name);
    }
}

有一個讀怎么關鍵字this作品在JS,這是一個有點棘手,但很容易掌握。

您可以這樣寫:

Orange.prototype.onCalled=function(){
    this.apple.onCalled.call(this);
}

很難給出一個普遍的答案。 要了解的是, this綁定在任何函數調用上。 可以通過callapply函數或通過顯式控制. 訪問函數作為對象的屬性時的運算符。

科斯給出的使用閉包的答案可能也很重要。 這取決於您想要的效果。

Orange.prototype.onCalled=function(){
    this.apple.onCalled.call(this);
}

示例: http//jsfiddle.net/XrtZe/

看看: JavaScript的范圍

暫無
暫無

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

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