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嗎?
問題解答
回答1:樓上講的沒問題,用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一樣回答2:
自己搞明白了,自問自答一下。這是js中典型的’this’變量的問題,在事件綁定函數中,回調函數最終是被事件綁定對象所調用,故此時的’this’指向該對象,此時想要將回調函數中的’this’變量指向實例對象,需要通過Function.prototype.bind手動改變this的指向。
