javascript String.prototype 的“this”不返回字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5146591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
a String.prototype's "this" doesn't return a string?
提问by adamJLev
What is going on here? Just when I thought I knew JS inside and out, this gem comes up.
这里发生了什么?就在我以为我从里到外都了解 JS 的时候,这个宝石出现了。
String.prototype.doNothing = function() {
return this;
};
alert(typeof 'foo'.doNothing()) // object
alert(typeof 'foo') // string
This is breaking some things that expect a string, such as jQuery's .text(str)method.
这打破了一些需要字符串的东西,比如 jQuery 的.text(str)方法。
采纳答案by Bob
Here's a thorough overviewof the thiskeyword. Basically, JavaScript converts it into an object, if it wasn't one.
这里有一个全面概述了的this关键字。基本上,JavaScript 将它转换为一个对象,如果它不是一个对象。
The following steps are performed when control enters the execution context for function code contained in function object F, a caller provided thisValue, and a caller provided argumentsList:
- If the function code is strict code, set the ThisBinding to thisValue.
- Else if thisValue is null or undefined, set the ThisBinding to the global object.
- Else if Type(thisValue) is not Object, set the ThisBinding to ToObject(thisValue).
- Else set the ThisBinding to thisValue
当控制进入函数对象 F 中包含的函数代码的执行上下文时,执行以下步骤,调用者提供 thisValue,调用者提供 argumentsList:
- 如果函数代码为严格代码,则将ThisBinding 设置为thisValue。
- 否则,如果 thisValue 为 null 或未定义,则将 ThisBinding 设置为全局对象。
- 否则,如果 Type(thisValue) 不是 Object,则将 ThisBinding 设置为 ToObject(thisValue)。
- 否则将 ThisBinding 设置为 thisValue
Same thing happens to Numbers and Booleans. A similar DoNothingfunction would return a type of object.
同样的事情发生在数字和布尔值上。类似的DoNothing函数将返回一种对象类型。
回答by McHerbie
To make sure you're always getting a string, trying using this code:
为确保您始终获得一个字符串,请尝试使用以下代码:
String.prototype.doNothing = function() {
return this.toString();
};
alert(typeof 'foo'.doNothing())
alert(typeof 'foo')
In your original code, thisis being returned as the string object and not the actual string.
在您的原始代码中,this作为字符串对象而不是实际字符串返回。
回答by everconfusedGuy
Run your code in strictmode to get your expected result!
以strict模式运行您的代码以获得预期的结果!
回答by KooiInc
You could've also used the constructorproperty:
您也可以使用该constructor属性:
'foo'.constructor === String; //=>true
'foo'.doNothing().constructor === String; //=>true
See also this SO questionand this jsFiddle
另见this SO question和this jsFiddle
If String.prototype.doNothing()breaks stuff expecting a string value, I would use return String(this)or this.toString()(this.valueOf()also works here) indeed.
如果String.prototype.doNothing()打破期待字符串值的东西,我会使用return String(this)or this.toString()(this.valueOf()也适用于这里)确实。
回答by naivists
It's again the difference between string literals and strings, i believe? I once had a question answered here in SO: Property value of a String object in JavaScript
这又是字符串文字和字符串之间的区别,我相信吗?我曾经在 SO 中回答过一个问题:JavaScript 中 String 对象的属性值
回答by nedk
To get a better understanding of what's going on try using console logs, like so:
为了更好地了解正在发生的事情,请尝试使用控制台日志,如下所示:
String.prototype.doNothing = function() {
console.log(this);
return this;
};
console.log(typeof 'foo'.doNothing());
console.log(typeof 'foo');
These are the results I get in Firefox:
这些是我在 Firefox 中得到的结果:
foo { 0="f", 1="o", more...}
object
string
So it seems in the prototype a string is represented as an object/an array of characters (which does make sense.)
因此,在原型中,字符串似乎表示为对象/字符数组(这确实有意义。)
Whether or not you should use toString (as suggested by McHerbie) or casting as a type String (as suggested by mellamokb) depends, in my opinion, on what you plan to do with this value. I would personally lean toward casting it as a String.
在我看来,您是否应该使用 toString(如 McHerbie 所建议的那样)或转换为类型 String(如 mellamokb 所建议的那样)取决于您打算对这个值做什么。我个人倾向于将其转换为字符串。
回答by user2240578
try the following:
尝试以下操作:
return this + '';
回答by dovid crow
function print() {
let str = this;
console.log(str);
}
String.prototype.print = print;
let a = "hello";
a.print();//output:"hello"

