开发者

Javascript apply or call used on charCodeAt

The premise: what the correct charCodeAt(i : Int) performance would look like:

"test".charCodeAt(0)
116
"test".charCodeAt(1)
101
"test".charCodeAt(2)
115
"test".charCodeAt(3)
116
"test".charCodeAt(4)
NaN

and here what happens when when using call or 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

The arguments are passed correctly. It is about the scope of which is passed with the first argument of call or apply and changes the valueOf from the this pointer.

I am not really sure what happened, and couldn't reproduce the behaviour in a new console window (Chrome v15):

x = "test"
"test"

"".charCodeAt.call(this.x,0)
116
OK.

As to the question: When the scope is not specified with this.x but only x -in this exampl-e, can odd behaviour re开发者_运维百科sult owing to the scope-resolution of the JS interpreter? Did someone encounter similar cases with strange scope-conflicts?


In all those calls like:

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

the value of this is likely to be window, not any string value. Try this:

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

If you pass in something bogus for this, you can't expect it to work properly :-) The reason it works when you define a variable "x" and then refer to "this.x" is, again, that this is window, so "this.x" is the same as "window.x", which will get you your variable.


this is window in your case and window.toString() === "[object Window]". So you are working with that string.

If you want the charCodeAt function better use var foo = String.prototype.charCodeAt; and then call it on some string: foo.call('meow', 0)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜