gpt4 book ai didi

javascript - 使用 jQuery 应用 OOP

转载 作者:数据小太阳 更新时间:2023-10-29 05:13:42 25 4
gpt4 key购买 nike

我正在使用 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; });

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

有什么办法吗?

最佳答案

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

通过调用

.hover(my_zoomin.hoverOn,...)

你只是传递了函数。它不会“记住”它属于哪个对象。你可以做的是传递一个匿名函数并在里面调用hoverOn:

.hover(function(){ my_zoomin.hoverOn(); },...)

这将使 hoverOn 中的 this 引用 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;
});

下一步,您可以考虑制作 jQuery plugin .

关于javascript - 使用 jQuery 应用 OOP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5852560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com