js中this的用法
I am creating a Javascript object that contains a function that executes a jQuery each method like the following:
function MyClass {
Method1 = function(obj) {
// Does something here
}
Method2 = function() {
$(".SomeClass").each(function() {
// 1 2
this.Method1(this);
});
}
}
I guess you could do something like this:
function MyClass {
Method1 = function(obj) {
//do something here
}
Method2 = function () {
var containingClass = this;
$(".SomeClass").each(function () {
containingClass.Method1(this);
});
}
}
}
This means that every time the passed-in function is executed (which is once for every element matched) the 'this' keyword points to the specific DOM element. Note that 'this' does not point to a jQuery object.
Personally, I prefer using explicit parameters. This way, it is more easily readable:
$('#rotfl').each(function(index, domObject)
{
var jQueryObject = $(domObject);
// code
});
To answer your question: JavaScript has dynamic static scope. You can do the following:
var that = this;
$('#rotfl').each(function(index, domObject)
{
var jQueryObject = $(domObject);
that.DoSomething();
// code
});
this是js的一个关键字,随着函数使用场合不同,this的值会发生变化。但是总有一个原则,那就是this指的是调用函数的那个对象。
1、纯粹函数调用。
function test() { this.x = 1; alert(x);}test();
复制代码
其实这里的this就是全局变量。看下面的例子就能很好的理解其实this就是全局对象Global。
var x = 1;function test() { alert(this.x);}test();//1var x = 1;function test() { this.x = 0;}test();alert(x);//0
复制代码
2、作为方法调用,那么this就是指这个上级对象。
function test() { alert(this.x);}var o = {};o.x = 1;o.m = test;o.m(); //1
复制代码
3、作为构造函数调用。所谓构造函数,就是生成一个新的对象。这时,这个this就是指这个对象。
function test() { this.x = 1;}var o = new test();alert(o.x);//1
复制代码
4、apply调用
this指向的是apply中的第一个参数。
var x = 0;function test() { alert(this.x);}var o = {};o.x = 1;o.m = test;o.m.apply(); //0o.m.apply(o);//1
复制代码
当apply没有参数时,表示为全局对象。所以值为0。