闭包

关于Javascript中类成员函数中内嵌函数的this闭包问题

之前写CocosLua和CocosJS时经常会遇到类成员函数中调用内嵌函数时的this传递问题,最近发现Javascript中可以通过使用箭头函数简化这个this的闭包问题,先给出测试代码:

class clsTest {
  constructor(var1) {
    this._var1 = var1;
  }

  foo() {
    console.log("1111", this._var1);

    (() => {
      console.log("2222", this._var1);
    })();

    (function() {
      console.log("3333", this);
    })();

    let self = this;
    (function() {
      console.log("4444", self._var1);
    })();
  }
}

let objTest = new clsTest(10);
objTest.foo();

JSFiddle:https://jsfiddle.net/u0yconbg/2/

为了简化示例代码,内嵌函数都写成了自调用的形式,可见333时的内嵌函数调用this是undefined,所以4444时在调用函数前声明了self用于闭包进内嵌函数访问this,(Lua中一般是local this = self),而2222的内嵌函数是通过箭头方式声明的,可见log中成功输出了clsTest类对象的_var1成员变量值,也就是说this被自动传递了,为此特意查了下文档:

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

来自:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

关于Javascript闭包closure的应用

最近在研究百度地图API的应用,试验了iOS SDK后又开始试验Web端的JS版应用,做到在地图上通过Ajax异步调用方式从后端取得数据后,添加标注并给标注添加对应的点击时间alert出此位置的信息时遇到了一个Javascript问题,最开始的code是这样写的:

		$.ajax({
			type : "get",
			url : urlStr,
			async : true,
			dataType : "json",
			error : function() {
				alert('No valid location record!');
			},
			success : function(json) {
				for(var i=0;i<json.length;i++)
				{
					var point = new BMap.Point(json[i].longtitude, json[i].latitude); 
					var marker = new BMap.Marker(point);        // 创建标注  
                                        // 添加点击事件侦听
					mark.addEventListener("click", function()
			                {
				            alert('记录时间: '+json[i].logTime+' 定位时间: '+json[i].gpsTime);
				            return;
			                });
					map.addOverlay(marker);                     // 将标注添加到地图中 
				}
		        var point = new BMap.Point(json[0].longtitude, json[0].latitude);  
        		map.centerAndZoom(point, 15);
			}
			});

这样运行时,点击任意一个标注后就会收到浏览器的js脚本错误,提示json[i].logTime还有后面同样的gpsTime部分有问题,检查了一下,发现Ajax请求成功后的函数内循环遍历数据时的i是局部变量,而每一个mark的click侦听函数内的i都为对同一个变量的引用,也就是说循环遍历后每次点击触发执行这段响应代码时的i都是同一个数,而不是认为的对应每一个mark时的i,也自然就取不到所期望的数据了!
Continue reading…