说说Javascript的bind()

我们都知道,对于Javascript的运行时this来说,函数进回调之前一定要保存this,通常的做法如下:

1
var _that = this;	//用一个局部变量保存this的值再进放回调callback

本来通常情况下处理函数都要用一层匿名函数包裹一下,才能维持处理函数本身的this.也可以直接通过.bind(logger)人为的将其执行时的this指向logger对象。

而且有个比较好用说起来又复杂的情况是与函数的闭包一起使用,例子是我用cocosjs写的一段代码,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//闭包嵌套
ccs.armatureDataManager.addArmatureFileInfo(FynnFlashPath + "songli.ExportJson");
var temp = new Array();
this._armature = new ccs.Armature("songli");
this._armature.getAnimation().play("songli",-1,0);
this._armature.x = cc.winSize.width / 2;
this._armature.y = cc.winSize.height / 2;
temp.push(this._armature);
this._armature.getAnimation().setMovementEventCallFunc(function(armature, movementType, movementID) {
if (movementType == ccs.MovementEventType.complete) {
var toBig = cc.scaleTo(0.2,1.2);
var toSmall = cc.scaleTo(0.2, 0);
var toFade = cc.fadeOut(0.2);
var spawn = cc.spawn(toSmall,toFade);
var seqScale = cc.sequence(toBig,spawn,cc.callFunc(function(selectorTarget){
if(temp!=null){
temp[0].removeFromParent(true);
cc.log("动画Release!")
}
}, temp));
temp[0].runAction(seqScale);
}
}.bind(this));

this.addChild(this._armature,200);