Lor*_*uer 5 javascript browser scope this call
前提:正确的charCodeAt(i:Int)性能如何:
"test".charCodeAt(0)
116
"test".charCodeAt(1)
101
"test".charCodeAt(2)
115
"test".charCodeAt(3)
116
"test".charCodeAt(4)
NaN
Run Code Online (Sandbox Code Playgroud)
在这里使用电话或申请时会发生什么:
>"test".charCodeAt.apply(this, [0,1,2,3])
91
//that's fine, except for 91!
"test".charCodeAt.call(this,0)
91
"test".charCodeAt.call(this,4)
101
"test".charCodeAt.call(this,5)
99
"test".charCodeAt.call(this,50)
NaN
"test".charCodeAt.call(this,6)
116
"test".charCodeAt.call(this,8)
68
x = "test".charCodeAt
function charCodeAt() { [native code] }
x.call(x,0)
102
Run Code Online (Sandbox Code Playgroud)
参数正确传递.它是通过call或apply的第一个参数传递的范围,并从this指针更改valueOf .
我不确定发生了什么,并且无法在新的控制台窗口(Chrome v15)中重现该行为:
x = "test"
"test"
"".charCodeAt.call(this.x,0)
116
OK.
Run Code Online (Sandbox Code Playgroud)
关于这个问题:当没有用this.x指定范围但只有x -in这个例子时,由于JS解释器的范围分辨率,可能会产生奇怪的行为吗?有人遇到类似的奇怪范围冲突案件吗?
在所有这些电话中:
"test".charCodeAt.call(this, 0);
Run Code Online (Sandbox Code Playgroud)
值this可能是window,而不是任何字符串值.试试这个:
var string = "test";
string.charCodeAt.call(string, 0);
Run Code Online (Sandbox Code Playgroud)
如果你传递了一些虚假的东西this,你不能指望它能正常工作:-)当你定义变量"x"然后引用"this.x"时,它的工作原理再次this就是window这样," this.x"与"window.x"相同,它将为您提供变量.