JS对象this.method()通过jQuery中断 [英] JS Object this.method() breaks via jQuery
问题描述
我确信这有一个简单的答案,但是周五下午我很累。 :(
I'm sure there's a simple answer to this, but it's Friday afternoon and I'm tired. :(
不知道如何解释它,所以我会继续发布示例代码......
Not sure how to explain it, so I'll just go ahead and post example code...
这是一个简单的对象:
Here is a simple object:
var Bob =
{ Stuff : ''
, init : function()
{
this.Stuff = arguments[0]
}
, doSomething : function()
{
console.log( this.Stuff );
}
}
此处正在使用:
$j = jQuery.noConflict();
$j(document).ready( init );
function init()
{
Bob.init('hello');
Bob.doSomething();
$j('#MyButton').click( Bob.doSomething );
}
一切正常,除了最后一行。当jQuery调用doSomething方法时,它会覆盖'this'
Everything works, except for the last line. When jQuery calls the doSomething method it is overriding 'this' and stopping it from working.
尝试仅使用 Stuff
也不起作用。
Trying to use just Stuff
doesn't work either.
那么如何以允许jQuery调用它的方式引用对象自己的属性,并且还允许该对象使用调用jQuery对象?
So how do I refer to an object's own properties in a way that allows jQuery to call it, and also allows the object to work with the calling jQuery object?
即我希望能够做到这样的事情:
i.e. I would like to be able to do things like this:
doSomething : function()
{
console.log( <CurrentObject>.Stuff + $j(<CallerElement>).attr('id') );
}
(其中< CurrentObject>
和< CallerElement>
将替换为相应的名称。)
(Where <CurrentObject>
and <CallerElement>
are replaced with appropriate names.)
推荐答案
这个
的身份是javascript中的常见问题。如果您尝试创建 doSomething
的快捷方式,它也会中断:
The identity of this
is a common problem in javascript. It would also break if you tried to create a shortcut to doSomething
:
var do = Bob.doSomething;
do(); // this is no longer pointing to Bob!
最好不要依赖这个$ c的身份$ C>。您可以通过多种方式实现这一目标,但最简单的方法是在<
。另一个是使用构造函数(但是你失去了酷的对象 - 文字语法): Bob
而不是此
code> doSomething的
It's good practice to not rely on the identity of this
. You can do that in a variety of ways, but the easiest is to explicitly reference Bob
instead of this
inside of doSomething
. Another is to use a constructor function (but then you lose the cool object-literal syntax):
var createBob = function() {
var that = {};
that.Stuff = '';
that.init = function() {
that.Stuff = arguments[0];
};
that.doSomething = function() {
console.log( that.Stuff );
};
return that;
}
var bob = createBob();
这篇关于JS对象this.method()通过jQuery中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!