【发布时间】:2011-10-30 16:33:42
【问题描述】:
前提:正确的 charCodeAt(i : Int) 性能应该是什么样子:
"test".charCodeAt(0)
116
"test".charCodeAt(1)
101
"test".charCodeAt(2)
115
"test".charCodeAt(3)
116
"test".charCodeAt(4)
NaN
以及使用 call 或 apply 时会发生什么:
>"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
参数正确传递。它是关于与 call 或 apply 的第一个参数一起传递的范围,并从 this 指针更改 valueOf。
我不确定发生了什么,并且无法在新的控制台窗口 (Chrome v15) 中重现该行为:
x = "test"
"test"
"".charCodeAt.call(this.x,0)
116
OK.
至于问题:当范围没有用 this.x 指定但只有 x -在这个例子中,可以 奇怪的行为 em> 结果是由于 JS 解释器的作用域解析吗? 有人遇到过奇怪的范围冲突的类似案例吗?
【问题讨论】:
-
我刚刚看了你的博客,你正在扩展宿主对象的原型。这通常很危险。不过对于
String,它是安全的。但请永远不要尝试为Array或Object这样做。 -
@ThiefMaster 好吧,这可能不是每个人都喜欢做的事情,但是一些库(功能、原型)使用原生对象的扩展作为基本的架构方法。
标签: javascript browser scope call this