2014-12-01 93 views
2

我试图在对象中使用_.throttle,但我认为我不知道如何正确执行此操作。在对象中使用下划线油门 - 如何保持对象的引用?

我使用jQuery和Underscore.js

function object() { 
    this.throtthled = function() { 
     // This should alert 1 
     alert(this.var); 
    } 

    this.fastFunc = _.throttle(this.throtthled, 100); 
    this.var = 1; 
} 


$(function() {  
    var myObject = new object(); 
    $(document).on('mousemove', myObject.fastFunc);  
}); 

但你可以在控制台上看到jsfiddle,这只回报undefined。 我在做什么错?

+0

您在创建它之前正在访问'this.throtthled'。 – Bergi 2014-12-01 20:30:24

+0

你说得对。我修复了它,无法访问'this.var'。任何想法 ? – 2014-12-01 20:34:49

+0

看到我的答案 – Bergi 2014-12-01 20:35:52

回答

4

您在创建它之前正在访问this.throtthled,并将undefined传递给_.throttle而不是函数(其方法为.apply)。

此外,您需要use the correct this context为您的回调。

// using the prototype: 
function MyObject() { 
    this.fastFunc = _.throttle(this.throttled.bind(this), 100); 
    this.var = 1; 
} 
MyObject.prototype.throttled = function() { 
    // This does alert 1 
    alert(this.var); 
}; 
+0

它的工作原理!谢谢。如果我想给fastFunc一个参数怎么办? – 2014-12-01 20:44:10

+1

只给'throttled'一个参数。 '_.throttle'传递任何给定的参数。 – Bergi 2014-12-01 20:45:06

+0

非常感谢。我将深入了解Prototype。 – 2014-12-01 20:59:56