I’m reading Crockford’s ‘JS: The Good Parts’. He has two examples using this and I don’t understand why in one instance he uses this and in another he uses that.
The first example:
String.method('deentify', function() {
var entity = {
quot: '"',
lt: '<',
gt: '<'
};
return function() {
return this.replace(/&([^&;]+);/g,
function (a, b) {
var r = entity[b];
return typeof r === 'string' ? r : a;
}
);
};
}());
document.writeln('<">'.deentify());
The second example:
Function.method('curry', function() {
var args = arguments, that = this;
return function () {
return that.apply(null, args.concat(arguments));
};
});
var add1 = add.curry(1);
document.writeln(add1(6));
Why can the first example access this directly? What is the difference between that example and the one that follows it?
When you do
obj.f(),thisinside the functionfwill refer toobj.In the first example,
deentify()is called on a string. In that function, he only needs the object on which the function was called, the string, which is whatthisinside thedeentify()function is going to refer to.Why we need
thatThe
add1function needs to store a reference to the originaladdfunction somehow.add1cannot usethis, because it is not called asadd.add1. This is overcome by creating a closure overthat, in which he saves the reference to the function you executecurry()on (add()in the example).When you call
add.curry(),thiswill refer to theaddfunction. (Because you calledcurry()onadd). Due to the closure inside the curry function,thatwill keep its value and will still reference theaddfunction whenadd1()is called.If
thiswas used inside the function returned fromcurry(), it would refer to thewindowobject.Note: It is important to see, that the first
returnin the first snippet denotes thedeentify()function, whereas the firstreturnin the second snippet denotes the return value of thecurry()function.If you want to understand the
arguments/apply()magic that makes curry work as well, just ask in the comment, I’ll be happy to elaborate.