簡體   English   中英

如何將實例函數傳遞給外部函數?

[英]how do you pass an instance function to an outside function?

假設我在名為file1.js的文件中包含以下內容:

//constructor
function Blah(){

    this.string = "hello there agent ";

}

//'method'
Blah.prototype.greeting = function(num){
    return  this.string + num;
}

然后在一個名為file2.js的文件中,我有以下內容:

function combine(num,funct){
    return funct(num);
}

最后,在一個名為file3的html文件中,我有以下內容:

var bond = new Blah();
document.write(combine(007,bond.greeting));

我實際上正在進入“ greeting”方法,但是由於某種原因,返回值不是字符串,而是不是NaN。 知道為什么嗎? greeting()方法似乎在適當的時間運行。 但是,盡管如此,無論如何,007似乎還是被解釋為NaN。 同樣,關於什么可能導致這種情況的任何建議?

提前謝謝一堆

首先,取決於您如何調用greeting方法, this值將有所不同。 如果你這樣稱呼它bond.greeting(num)那么this將是bond 如果您像funct(num)那樣調用它,其中functbond.greeting ,則this將是全局對象。 您需要綁定this永久沿着傳遞功能時,要無論你如何調用該函數保持其價值。

其次, 007 === 7 如果要從字面上打印出007 ,則應使用一個字符串:

combine('007', bond.greeting.bind(bond));

記住, this取決於函數的調用方式,它是動態的以及如何解析運行時的,除非您像前面那樣綁定了它,否則就不行了。

您正在體驗this關鍵字的特殊特征。

基本上, this可以解決您從中調用函數的任何問題。 在您的情況下,您是通過func()從全局范圍調用它的,這使this == window (通過bond.greeting()進行調用使this == bond 。)

要解決此問題,可以bind函數或強制執行分辨率:

// note that this method requires a shim for IE 8 and older
document.write(combine(007,bond.greeting.bind(bond)));

要么

function combine(num, obj, funct){
    // since funct is being called from obj, `this` == obj within the function
    return obj[funct](num);
}

document.write(combine(007,bond, 'greeting'));    

1)NaN為“非數字”錯誤。 嘗試將007封裝在引號中2)您是否需要file2.js還是沒有它?

var bond = new Blah();
document.write(bond.greeting("007"));

您遇到的問題是,當您將函數作為參數傳遞時,它通過值傳遞,然后您將對元素string = "hello there agent ";的對象的引用放開string = "hello there agent "; 當執行該函數時,它將執行該函數中不存在的"this.string" ,並返回undefined 這是一個范圍問題。

使它工作良好的解決方案是通過引用即對象bond

function combine(num,obj){
    return obj.greeting(num);
}

combine("007",bond); // returns "hello there agent 007"

暫無
暫無

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

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