2015-01-06 46 views
1
Function.prototype.defer = function(ms) { 
    var self = this; 

    return function() { 
     setTimeout(self, ms); 
    }; 
} 

function f(a, b) { 
    alert(a + b); 
} 

f.defer(5000)(1, 2); // 3 

應該在5秒內顯示數字3,但以某種方式推斷出NaN。損失的上下文。 setTimeout

+1

您還沒有傳遞的參數一起 – epascarello

回答

2

這是因爲,您將setTimeout的功能,但參數1, 2不綁定到它,所以它調用f不帶參數。

你能解決這個問題是這樣的:

Function.prototype.defer = function(ms) { 
    var self = this; 

    return function() { 
     var args = arguments, 
      context = this; 

     setTimeout(function() { 
      self.apply(context, args); 
     }, ms); 
    }; 
} 

function f(a, b) { 
    alert(a + b); 
} 

f.defer(5000)(1, 2); // 3 
+0

確定。我都明白了。非常感謝你! – Aleksandr

3

defer返回的函數不帶任何參數,因此12被忽略。

如果你想使用它們,那麼你需要捕獲它們並對它們做些什麼。

Function.prototype.defer = function(ms) { 
 
    var self = this; 
 

 
    return function(x, y) { 
 
     setTimeout(self.bind(this, x, y), ms); 
 
    }; 
 
} 
 

 
function f(a, b) { 
 
    alert(a + b); 
 
} 
 

 
f.defer(5000)(1, 2); // 3