首頁  >  問答  >  主體

javascript - 事件綁定函數中this是事件的綁定的對象,怎麼能在該函數中引用實例化對象?

用的Leaflet框架,準備擴充一個物件。
程式碼如下:

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和triggerLyrChange都是事件綁定函數,函數中的this就是物件的_map,怎麼在這個函數裡面正確引用實例化物件?只能用FxtMap.prototype嗎?

扔个三星炸死你扔个三星炸死你2663 天前749

全部回覆(2)我來回復

  • 大家讲道理

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

    樓上講的沒問題,用bind就行,或者你可以自己模擬一個bind,

    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一样

    回覆
    0
  • 習慣沉默

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

    自己搞懂了,自問自答一下。
    這是js中典型的'this'變數的問題,在事件綁定函數中,回調函數最終是被事件綁定對象所調用,故此時的'this'指向該對象,此時想要將回調函數中的'this'變數指向實例對象,需要透過Function.prototype.bind手動改變this的指向。

    回覆
    0
  • 取消回覆