javascript - 事件绑定函数中this是事件的绑定的对象,怎么才能在该函数中引用实例化对象?

查看:79
本文介绍了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吗?

解决方案

楼上讲的没问题,用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一样

这篇关于javascript - 事件绑定函数中this是事件的绑定的对象,怎么才能在该函数中引用实例化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆