0

I try to use the following structure in my app: https://gist.github.com/jonnyreeves/2474026

I try to register some callback inside my constructor. I made an example using jquery, actually it's leaflet maps, but the difference shouldn't matter.

function Person() {
    this.name = "abc";

    $("#something").onSomeEvent(function() {
        this.name = "cde";
    });
}

How do I properly reference my object-property name, inside the callback?

4

3 回答 3

3

你可以使用这样的东西:

function Person() {
    this.name = "abc";
    $("#something").onSomeEvent(function() {
        this.name = "cde";
    }.bind(this));
}
于 2013-08-23T11:20:43.000 回答
2
   function Person() {
        var self = this;
        self.name = "abc";
        $("#something").onSomeEvent(function() {
            //this is right if you need
            self.name = "cde";
        });
    }

您可以将 $('#someting') 与this一起使用。

如果你使用bind来解决问题,在回调中是错误的。

于 2013-08-23T11:24:18.733 回答
1

使用bind,在较旧的 IE 或 jquery 中不支持proxy

function Person() {
    this.name = "abc";

    $("#something").onSomeEvent(function() {
        this.name = "cde";
    }.bind(this));
}


function Person() {
    this.name = "abc";

    $("#something").onSomeEvent($.proxy(function() {
        this.name = "cde";
    },this));
}
于 2013-08-23T11:23:58.143 回答