0

我在小部件内失去范围时遇到问题。在 _initialize 内部,this.options不起作用,that.options. 如何从此方法访问小部件的范围?

$.widget("myproj.map", {
        options: {
            centerLat: 51.511214,
            centerLong: -0.119824,
        },

        // the constructor
        _create: function () {
            var that = this;
            google.maps.event.addDomListener(window, 'load', this._initialize);
        },
        _initialize: function () {

            var mapOptions = {
                center: new google.maps.LatLng(that.options.centerLat, that.options.centerLong),
                zoom: 11,
            };

澄清

$.widget("myproj.map", {
        options: {
            centerLat: 51.511214,
            centerLong: -0.119824,
        },

        // the constructor
        _create: function () {
            google.maps.event.addDomListener(window, 'load', this._initialize);
        },
        _initialize: function () {
            console.log(this);
            var mapOptions = {
                center: new google.maps.LatLng(this.options.centerLat, this.options.centerLong),
                zoom: 11
            }; ...code omitted

不起作用,当我在 _initialize 中 console.log 时,我得到

Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}
4

2 回答 2

1

google.maps.event.addDomListener改变this所指的东西。您可以通过调用绑定方法将其更改回来

google.maps.event.addDomListener(window, 'load', this._initialize.bind(this));
于 2013-12-05T00:47:44.910 回答
0

编辑:这个答案确实解决了由事件处理程序引起的重新绑定

var that范围在_create函数内部,您应该能够this 从 initialize 内部访问。

new google.maps.LatLng(this.options.centerLat, this.options.centerLong)

查看有关“this”的类似问题

于 2013-12-05T00:30:10.353 回答