4

オブジェクト関数 (つまり .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
}

ヘルプ?

4

3 に答える 3

7

のコピーを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
}
于 2012-08-16T20:24:40.067 に答える
3

.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));
};
于 2012-08-16T20:31:59.357 に答える
1

反復する前に、参照するオブジェクトを定義できます。それはまだ範囲内にあるので、あなたはそれに近づくことができるでしょう。

var currentObject = this;

test.prototype.init = function(node) {
    node.children().each(function() {
        currentObject.anotherFunction();
    });
}
test.prototype.anotherFunction = function() {
    //whatever
}
于 2012-08-16T20:26:37.860 に答える