English 中文(简体)
当使用方法原型时, 将其传递到 jQuery 中的方法
原标题:passing this to methods in jQuery when using prototyping of methods

我用的是以下的代码

function Basket () {
  this.items = new Array();
}
Basket.prototype.addItem = function(item) {
  this.items.push(item);
  setTimeout(this.showItems, 1000);
};
Basket.prototype.showItems = function() {
  console.log( items in Basket:  +this.items.join( ,  ));
}

var b = new Basket()
b.addItem( bananas )
// -> Uncaught TypeError: Cannot call method  join  of undefined

When calling the addItem method, the showItems method is called properly, but in the showItems method the variable "this" does not reference to the Basket object. Using the Prototype framework I could do something like

setTimeout(this.showItems.bind(this), 1000)

这将将变量“ 此” 与显示项目方法中的篮子对象捆绑在一起 。

问题:在jQuery中,我怎样才能做到这一点?是否有比这样包装调用方法更优雅的方法(最佳做法)?

// ...
  $this = this
  setTimeout(function() {$this.showItems($this)}, 1000)

Basket.prototype.showItems = function ($this) {
  console.log( items in Basket:  +$this.items.join( ,  ));
}

如果有人能张贴一些有用的关键词,我也会很高兴的,如果有人能张贴一些有用的关键词,我如何能够找到这些问题,正如我肯定的那样,我不是唯一的一个问这个问题的人。 但自然,在您没有框架的时候,寻找“原型”是非常困难的,而寻找对象的延伸(或如何称呼它 ) 。

十六进

最佳回答

幸运的是,jQuery提供了一种 $.proxy 方法,其功能与原型提供的 >bind 功能相同。

可在http://api.jquery.com/jQuery.proxy/ 上查阅文件网页。

Hope that helps, Dave

问题回答

为什么不简单地在篮子中增加方法呢?

function Basket () {
  var items = new Array();
  this.addItem = function(item) {
     items.push(item);
     setTimeout(this.showItems, 1000);
   };
   this.showItems = function() {
      console.log( items in Basket:  + items.join( ,  ));
   };
};




相关问题
Python: Binding method

In following example I am trying to bind a method object via types.MethodType(...). It does not seem to work. Any suggestions? Thanks in advance. import types class Base: def payload(self, *args)...

Invoking an instance method without invoking constructor

Let s say I have the following class which I am not allowed to change: public class C { public C() { CreateSideEffects(); } public void M() { DoSomethingUseful(); } } and I have to call M ...

Behaviour of final static method

I have been playing around with modifiers with static method and came across a weird behaviour. As we know, static methods cannot be overridden, as they are associated with class rather than instance....

Setting the Page-Title in .Net using C# from a Class

Question, How do i set the title of a page from a class. Is it even possible? I can and have set the page title from a page itself and a usercontrol. Can I, How Do I do this via a class using C# ....

how to drag in the animation in iphone application?

Iphone application is using the static co-ordinates to reach at some points in the application,which is based on the button event. But what i want is when i drag the item than it should reach at some ...

热门标签