search

Home  >  Q&A  >  body text

javascript - In the event binding function, this is the object bound to the event. How can I reference the instantiated object in the function?

Use the Leaflet framework and prepare to extend an object.
code show as below:

var FxtMap = L.Class.extend({
        _preZoom: 4,
        _initZoom: 4,
        _queryScale: 7,
        _map:null,
        fxtData: null,
        options: {
            center: [31.2, 121.46715194],
            zoom: 4,
            crs: sh_crs,
            doubleClickZoom: false,
            zoomControl: false,
            attributionControl: false
        },

        initialize: function (id, mapOption) {
            if (mapOption) {
                L.Util.setOptions(this, mapOption);
            }

            this._map = L.map(id, this.options);

            m_tileLayer.addTo(this._map);
            m_oldView = this._map.getBounds();
            this._map.on({
                zoomstart: this.getPreZoom,
                zoomend: this.triggerLyrChange,
                viewreset: MapViewReset,
                moveend: MapDrag
            });
            this._map.invalidateSize("true");
        },
        getPreZoom: function (e) { 
            this._preZoom = this._map.getZoom();
        },
        triggerLyrChange: function () {
            if (this._map.getZoom() == this._queryScale && this._map.getZoom() > this._preZoom) {
                this._map.fire('jsonLyrType');
            }
            if (this.getZoom() == this._queryScale - 1 && this._map.getZoom() < this._preZoom) {
                this._map.fire('imgLyrType');
            }
        },
        
        ...
    })

getPreZoom and triggerLyrChange are both event binding functions. This in the function is the _map of the object. How to correctly reference the instantiated object in this function? Can I only use FxtMap.prototype?

扔个三星炸死你扔个三星炸死你2748 days ago828

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-07-05 10:57:22

    No problem as mentioned above, just use bind, or you can simulate a bind yourself,

    Function.prototype.NewBind = function(obj){
        var _self = this;
        return function(){
            _self.call(obj,arguments);
        };
    };
    
    //调用的话
    getPreZoom: function (e) { 
       this._preZoom = this._map.getZoom();
    }.NewBind(this)
    //和bind一样

    reply
    0
  • 習慣沉默

    習慣沉默2017-07-05 10:57:22

    You figure it out yourself, ask and answer your own questions.
    This is a typical problem with the 'this' variable in js. In the event binding function, the callback function is eventually called by the event binding object, so 'this' at this time points to the object. At this time, you want to change the callback function The 'this' variable points to the instance object, and you need to manually change the point of this through Function.prototype.bind.

    reply
    0
  • Cancelreply