I’ve a question about this reserved word in JavaScript.
Check out codes below:
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
}
};
String.method('deentityify', function () {
var entity = {
quot: '"',
lt: '<',
gt: '>'
};
return function () {
/*if (this === String.prototype) {
alert('true');
} else {
alert('false');
}*/
return this.replace(/&([^&;]+);/g,
function (a, b) {
var r = entity[b];
return typeof r === 'string' ? r : a;
}
);
};
}());
document.write('<">'.deentityify());
You can edit codes above at: http://jsfiddle.net/G3Tkm/
My question is:
What is the this reserved word at line 27 return this.replace(/&([^&;]+);/g, is?
I guess: this === String.prototype, but it isn’t.
The type of '<">' is string, and type of this is object. So this !== '<">'
Thank you very much!
Whenever I find a
thiskeyword in JavaScript code I usually just look upwards, until I find the surrounding function it’s in.Then I try and understand how this function gets called from the outside. This is important because the value of
thischanges based on how the function is being called.From your code it seems that
String.method()‘s job is to add methods to the prototype chain of the String object. This is something that you shouldn’t really do, it’s sort of bad JavaScript behavior and might cause some issues later on.However, for the sake of an explanation, whenever you call the
deentityifymethod on a string, such as"foo".deentityify()– suppose this calls whatever you assigned inString.method('deentityify', function () {–thisbecomes in effect another function itself (ifString.methodworks as I think).So, when using
"foo".deentityify()()yourthiswill refer to the caller, which is"foo".deentityify(). And the caller of"foo".deentityify()is in fact"foo"itself.So basically
this, in your case, refers to the String object you’re calling the method from.