Bil*_*ami 5 javascript oop scope
作为一个试图采用更加面向对象的方法进行我的javascript编程的人,我遇到了一个绊脚石我肯定可能是非常基本的东西,但是,采取以下对象实现(假设jQuery对象可用于这段代码):
function Foo()
{
this.someProperty = 5;
}
Foo.prototype.myFunc = function()
{
//do stuff...
};
Foo.prototype.bar = function()
{
//here 'this' refers to the object Foo
console.log(this.someProperty);
$('.some_elements').each(function()
{
//but here, 'this' refers to the current DOM element of the list of elements
//selected by the jQuery selector that jquery's each() function is iterating through
console.log(this);
//so, how can i access the Foo object's properties from here so i can do
//something like this?
this.myFunc();
});
};
Run Code Online (Sandbox Code Playgroud)
您可以暂时使用另一个变量指向正确此:
Foo.prototype.bar = function()
{
//here 'this' refers to the object Foo
console.log(this.someProperty);
var self = this;
$('.some_elements').each(function()
{
self.myFunc();
});
};
Run Code Online (Sandbox Code Playgroud)
在输入function传递给之前each,需要捕获this变量中的外部函数,然后使用function传递给它的变量each.
function Foo()
{
this.someProperty = 5;
}
Foo.prototype.myFunc = function()
{
//do stuff...
};
Foo.prototype.bar = function()
{
// in here, this refers to object Foo
// capture this in a variable
var that = this;
$('.some_elements').each(function()
{
// in here, this refers to an item in the jQuery object
// for the current iteration
console.log(that);
that.myFunc();
});
};
Run Code Online (Sandbox Code Playgroud)
如您所知,this在传递给函数的内部each引用每次迭代时jQuery对象中的当前项,即第一次迭代引用属性0处的项,第二次迭代引用属性1处的项等.