gpt4 book ai didi

Javascript 对象 - 使用 jQuery 和 this

转载 作者:搜寻专家 更新时间:2023-11-01 04:58:01 25 4
gpt4 key购买 nike

当在对象函数(即 .each())中使用 jQuery 方法时,“this”变量将引用被迭代的对象。如何在没有“this”的情况下访问对象的功能?我意识到这有点令人困惑,所以:

test.prototype.init = function(node) {
node.children().each(function() {
//call test.anotherFunction() here
//Would normally call this.anotherFunction(),
// but "this" refers to the current child.
});
}
test.prototype.anotherFunction = function() {
//whatever
}

帮忙吗?

最佳答案

this 的副本保存到局部变量中(在本例中名为 self,但您可以随意命名)并在嵌入式中使用保存的副本功能:

test.prototype.init = function(node) {
var self = this;
node.children().each(function() {
// use self here to reference the host object
});
}
test.prototype.anotherFunction = function() {
//whatever
}

关于Javascript 对象 - 使用 jQuery 和 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11994900/

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