在回调中访问类方法的正确方法[原型]

在回调中访问类方法的正确方法[原型]

问题描述:

我使用的是原型1.7,并构建了一个基本上需要divs列表并构建标签界面的类。在回调中访问类方法的正确方法[原型]

var tabs = Class.create({ 
    initialize: function(container, options) { 
     this.options = Object.extend({ 
      // additional options 
      tabsRendered: null, 
     }, options || {}); 

     // init code 

     if(this.options.tabsRendered) { 
      this.options.tabsRendered(); 
     } 
    }, 

    // additional methods 

    setCurrent: function(link){ 
     //adds a .current class to tab clicked and its corresponding section 
    } 
}; 

new vtabs('products', { 
    tabsRendered: function(){ 
     if(window.location.hash != "") { 
      var link = $$('a[href$="' + window.location.hash + '"]'); 
      this.setCurrent(link); 
     } 
    } 
}); 

我的问题涉及到我的tabsRendered自定义回调。当回调运行时,this.setCurrent(link)什么都不做。

如果我通过这个进入回调,我的自定义回调按预期工作。

if(this.options.tabsRendered) { 
    this.options.tabsRendered(this); 
} 

我的猜测是,通过步入回调是不是最好的做法。那么,我将如何允许从回调中访问方法?

感谢

问题是tabsRendered绑定。通过Prototype,您必须使用bind()绑定匿名函数。后// init code做:

if (Object.isFunction(this.options.tabsRendered)) 
    this.options.tabsRendered = this.options.tabsRendered.bind(this); 

之后,你可以调用this.options.tabsRendered()而且一旦匿名函数中,this将引用正确的对象。有关绑定的详细信息,请参见the Prototype API docs

编辑:正如评论:匿名函数不是唯一受影响的是正确的。它是函数被定义的范围中的this

+0

+1,但函数是匿名还是无关紧要,与绑定没有任何关系。另外,'bind'只是其中的几种方法之一(尽管它是一个很好的方法)。有关'this'的更多信息并确保您保留它:http://blog.niftysnippets.org/2008/04/you-must-remember-this.html和http://blog.niftysnippets.org/2008/03/ mythical-methods.html – 2010-12-10 18:17:33

+0

是的。我会重新相聚。 – 2010-12-10 18:21:01

+0

谢谢goreSplatter,你的建议帮了很大忙。奇怪的是,“Prototype.isFunction(this.option.tabsRendered)”不起作用。事实上,它导致脚本停止执行。 – jbarreiros 2010-12-10 19:41:00