適切なjavascriptコンテキストキャプチャ
, this — , — , . ?
var self = this;
?
, :
var self = this;
asyncFunc(function () {
self.callMethod();
});
(jQuery):
$('input').bind('keydown', function () {
var $this = $(this);
$this.css({
background : $this.val()
});
});
?
, self $this ( that, _this, t) . .
— . ,
var killmeplz = this;
— . , :
var self = this;
asyncFunc(function () {
var self2 = this; // wtf ?!!
setTimeout(function () {
self.callMethod(self2);
}, 200);
});
—
. JS, , . :
$('input').bind('keydown', function () {
var $colorInput = $(this);
$colorInput.css({
background : $colorInput.val()
});
});
.
$block = $(this);
$('button').each(function () {
var $button = $(this);
$.each(users, function () {
var user = this;
$block.append(user.init($button));
});
});
. :
MooTools . Function
Function.prototype.bind = function (scope) {
var fn = this;
return function () {
return fn.apply(scope, arguments);
};
};
. — :
asyncFunc(function () {
this.callMethod();
}.bind(this));
.bind
, , . ( MooTools):
var Analizer = new Class({
initialize : function (name) {
this.dataRouter = new DataRouter[name]();
},
start : function () {
var analizer = this;
this.dataRouter.get(function (data) {
analizer.parse(data);
});
},
parse : function (data) {
// parsing data, using this.privateMethods
}
});
get parse:
dataGetter.get(analizer.parse);
. bind , :
var Analizer = new Class({
initialize : function (name) {
this.dataRouter = new DataRouter[name]();
},
start : function () {
this.dataRouter.get(
this.parse.bind(this)
);
},
parse : function (data) {
// parsing data, using this.privateMethods
}
});
Bridge LibCanvas, bind.
, , .
, , , , .
Bridge.AI = new Class({
// ..
putCardSmart : function (card) {
this.putCard( card,
// , .
this.finishSmart.bind(this)
);
},
getCardSmart : function () {
this.getCard(function (card) {
this.canPutCard(card) ?
this.putCardSmart(card) :
this.finishSmart();
}.bind(this)); // .
},
finishSmart : function () {
this.canFinishMove() ?
this.finishMove() :
this.movement();
}
// ..
});
vl.vg/28.01.2010/tooltip-jquery
blog.kron0s.com/javascript-programming-patterns_2
habrahabr.ru/blogs/jquery/52185
All Articles