Heim  >  Fragen und Antworten  >  Hauptteil

javascript - In der Ereignisbindungsfunktion ist dies das an das Ereignis gebundene Objekt. Wie kann ich auf das instanziierte Objekt in der Funktion verweisen?

Verwendung des Leaflet-Frameworks zur Vorbereitung der Erweiterung eines Objekts.
Der Code lautet wie folgt:

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 und triggerLyrChange sind beide Ereignisbindungsfunktionen. Dies ist die _map des Objekts. Wie wird das instanziierte Objekt in dieser Funktion korrekt referenziert? Kann ich nur FxtMap.prototype verwenden?

扔个三星炸死你扔个三星炸死你2663 Tage vor747

Antworte allen(2)Ich werde antworten

  • 大家讲道理

    大家讲道理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一样

    Antwort
    0
  • 習慣沉默

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

    自己搞明白了,自问自答一下。
    这是js中典型的'this'变量的问题,在事件绑定函数中,回调函数最终是被事件绑定对象所调用,故此时的'this'指向该对象,此时想要将回调函数中的'this'变量指向实例对象,需要通过Function.prototype.bind手动改变this的指向。

    Antwort
    0
  • StornierenAntwort