用jQuery应用OOP

Ral*_*lph 6 javascript oop jquery javascript-events

我正在使用jQuery并尝试将一些基本的Javascript OOP原则应用于一组控制悬停行为的函数.但是,我无法弄清楚如何让"this"关键字引用我正在创建的对象的实例.我的示例代码是:

var zoomin = new Object();

zoomin = function() {
       // Constructor goes here
};

zoomin.prototype = {
       hoverOn: function() {
          this.hoverReset();
          // More logic here using jQuery's $(this)...
       },
       hoverReset: function() {
          // Some logic here.
       }
       };

// Create new instance of zoomin and apply event handler to matching classes.
var my_zoomin = new zoomin();
$(".some_class").hover(my_zoomin.hoverOn, function() { return null; });
Run Code Online (Sandbox Code Playgroud)

上面代码中有问题的行是在hoverOn()函数内调用"this.hoverReset()".由于"this"现在指的是悬停在其上的元素,因此它不能按预期工作.我基本上想要为该对象的实例(my_zoomin)调用函数hoverReset().

有没有办法做到这一点?

谢谢!

Fel*_*ing 8

仅将函数分配给对象的属性不会this在函数内部与对象关联.这是你调用函数的方式.

通过电话

.hover(my_zoomin.hoverOn,...)
Run Code Online (Sandbox Code Playgroud)

你只是传递了这个功能.它不会"记住"它属于哪个对象.你可以做的是传递一个匿名函数并调用hoverOn内部:

.hover(function(){ my_zoomin.hoverOn(); },...)
Run Code Online (Sandbox Code Playgroud)

这将使this内部hoverOn参考my_zoomin.所以呼吁this.hoverReset()将工作.但是,在内部hoverOn,您将不会引用选择器创建的jQuery对象.

一种解决方案是将所选元素作为参数传递:

var zoomin = function() {
   // Constructor goes here
};

zoomin.prototype = {
   hoverOn: function($ele) {
      this.hoverReset($ele);
      // More logic here using jQuery's $ele...
   },
   hoverReset: function($ele) {
      // Some logic here.
   }
};


var my_zoomin = new zoomin();
$(".some_class").hover(function() { 
    my_zoomin.hoverOn($(this));  // pass $(this) to the method
}, function() { 
    return null; 
});
Run Code Online (Sandbox Code Playgroud)

下一步,你可以考虑制作一个jQuery插件.