国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

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

瀏覽:122日期:2023-03-07 14:41:10

問題描述

用的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的指向。

標簽: JavaScript
主站蜘蛛池模板: 维西| 昭觉县| 崇礼县| 清流县| 云浮市| 新津县| 胶南市| 德保县| 基隆市| 无极县| 孟村| 巍山| 惠州市| 凌海市| 绍兴县| 泰安市| 乐亭县| 集安市| 海原县| 梨树县| 潢川县| 绥阳县| 西吉县| 丰台区| 安阳县| 洪江市| 山丹县| 田林县| 利津县| 玛纳斯县| 乌苏市| 蓝田县| 区。| 琼中| 临海市| 云梦县| 柳林县| 汝城县| 石景山区| 安溪县| 天柱县|