在 charCodeAt 上使用的 Javascript 应用或调用

标签 javascript browser scope call this

前提:正确的 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 解释器的范围解析? 有人遇到过具有奇怪范围冲突的类似案例吗?

最佳答案

在所有这些调用中,例如:

"test".charCodeAt.call(this, 0);

this 的值可能是window,而不是任何字符串值。试试这个:

var string = "test";
string.charCodeAt.call(string, 0);

如果你为 this 传递了一些伪造的东西,你就不能指望它能正常工作:-)当你定义一个变量“x”然后引用“this”时它能正常工作的原因。 x"再次表示 thiswindow,因此“this.x”与“window.x”相同,后者将为您提供变量。

关于在 charCodeAt 上使用的 Javascript 应用或调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7123140/

相关文章:

javascript - 动态更改字体大小时到基线的恒定距离 - html - 文本元素

C++:for循环的范围?

Java 变量范围 - 复制位图?

php - PHP 中 require_once 的范围是什么?

javascript - Istanbul 尔:使用 mocha 生成代码 cobertura 报告

java - 通过 AngularJS 上传文件后从 Spring Controller 返回 Json

javascript - 如何使用 Node 'http' 重定向到目标 url

browser - 缩放存储在 S3 中的图像

html - URL 中的 `#:~:text=` 如何突出显示文本?

android - 在 WebView 中启用长按