gpt4 book ai didi

JavaScript 作用域问题

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

作为一个试图对我的 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();
});
};

最佳答案

您可以暂时使用另一个变量来指向正确的this:

Foo.prototype.bar = function()
{
//here 'this' refers to the object Foo
console.log(this.someProperty);

var self = this;

$('.some_elements').each(function()
{
self.myFunc();
});
};

关于JavaScript 作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3670310/

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