Javascript对象-使用jQuery和

Javascript对象-使用jQuery和,javascript,jquery,object,this,javascript-objects,Javascript,Jquery,Object,This,Javascript Objects,在对象函数(即-.each())中使用jQuery方法时,“this”变量将引用正在迭代的对象。没有“this”我如何访问对象的函数?我意识到这有点混乱,所以: test.prototype.init = function(node) { node.children().each(function() { //call test.anotherFunction() here //Would normally call this.anotherFunctio

在对象函数(即-.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
}

帮助?

将此的副本保存到局部变量中(本例中名为
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
}

可以在迭代之前定义要引用的对象。您将能够接近它,因为它仍在范围内

var currentObject = this;

test.prototype.init = function(node) {
    node.children().each(function() {
        currentObject.anotherFunction();
    });
}
test.prototype.anotherFunction = function() {
    //whatever
}

您还可以使用
.bind
函数更改函数的上下文。无论您提供给
.bind
的参数是什么,它在执行时都将成为函数的所有者,因此,
this
的值

test.prototype.init = function(node) {
    node.children().each(function(i,el) {
        // this = test.prototype
        // i = index of the current child of `node`
        // el = HTML node of current child
        // $(el) = jQuery object representing current child
    }.bind(this));
};

+1
var self=this
通常用于保留父级的作用域如同
self
阴影笼罩着全球
窗口。self
回应@jbabey对
self
的关注。facepalm我不敢相信我没有想到这一点。使用“obj”会有什么顾虑吗?使我的大脑比“那”更快乐。
window。self
指的是
窗口的上下文。因此,用当前上下文对其进行阴影处理是有意义的。对象上方法的全部要点是,您可以引用调用该方法的对象。在进行方法调用之前设置一个全局变量,而不仅仅是在方法中使用实际的对象引用,这不是一种好的风格,而且容易出现各种潜在的问题。使用bind是一种很好的方法