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()
,this
inside the functionf
will 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 whatthis
inside thedeentify()
function is going to refer to.Why we need
that
The
add1
function needs to store a reference to the originaladd
function somehow.add1
cannot 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()
,this
will refer to theadd
function. (Because you calledcurry()
onadd
). Due to the closure inside the curry function,that
will keep its value and will still reference theadd
function whenadd1()
is called.If
this
was used inside the function returned fromcurry()
, it would refer to thewindow
object.Note: It is important to see, that the first
return
in the first snippet denotes thedeentify()
function, whereas the firstreturn
in 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.