我对 JavaScript 中的 this
保留字有疑问。
检查下面的代码:
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());
您可以在以下位置编辑以上代码:http://jsfiddle.net/G3Tkm/
我的问题是:
第27行的this
保留字是什么return this.replace(/&([^&;]+);/g,
是什么?
我猜:this === String.prototype
,但事实并非如此。
'<">'
的类型是string,this
的类型是object。所以 this !== '<">'
非常感谢!
最佳答案
每当我在 JavaScript 代码中找到 this
关键字时,我通常只是向上看,直到找到它所在的周围函数。
然后我尝试了解如何从外部 调用此函数。这很重要,因为 this
的值会根据函数的调用方式而变化。
从您的代码看来,String.method()
的工作是将方法添加到 String 对象的原型(prototype)链中。这是你不应该真正做的事情,它是一种糟糕的 JavaScript 行为,可能会在以后导致一些问题。
但是,为了便于解释,每当您在字符串上调用 deentityify
方法时,例如 "foo".deentityify()
- 假设这调用了 whatever你在 String.method('deentityify', function () {
中赋值 - this
实际上成为另一个函数本身(如果 String.method
有效如我所想)。
因此,当使用 "foo".deentityify()()
时,您的 this
将引用调用者,即 "foo".deentityify()
。 "foo".deentityify()
的调用者实际上是 "foo"
本身。
所以基本上 this
,在您的例子中,指的是您从中调用方法的 String 对象。
关于javascript - 关于JavaScript中 "this"保留字的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4601978/