userObj.getExtraData = function (cb) {
var that = this;
getAsyncData(function (data) {
that.extraData = data;
cb();
});
};
userObj.getExtraData(function () {
console.log(userObj.extraData);
});
You can get rid of those pesky variables (thiz, that, self, _this, whatever) by just using Function.prototype.bind like so:
userObj.getExtraData = function (cb) {
getAsyncData(function (data) {
this.extraData = data;
cb();
}.bind(this));
};
userObj.getExtraData(function () {
console.log(userObj.extraData);
});
Huzzah!! We've got "this" back!
Edit:
The new ES6 syntax makes this a lot easier with big arrow syntax. It gives you a shorthand for writing functions while auto-binding your context. This:
(data) => {
// do stuff
}
Is equivalent to this:
function (data) {
// do stuff
}.bind(this);
userObj.getExtraData = function (cb) {
getAsyncData((data) => {
this.extraData = data;
cb();
});
};
userObj.getExtraData(function () {
console.log(userObj.extraData);
});
No comments:
Post a Comment