Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 result owing to the scope-resolution of the JS interpreter? Did someone encounter similar cases with strange scope-conflicts?

like image 800
Lorenz Lo Sauer Avatar asked Aug 19 '11 14:08

Lorenz Lo Sauer


People also ask

What does charCodeAt do in Javascript?

The charCodeAt() method returns the Unicode of the character at a specified index (position) in a string. The index of the first character is 0, the second is 1, .... The index of the last character is string length - 1 (See Examples below). See also the charAt() method.

Can you use charCodeAt on Array?

Array doesn't have charCodeAt method.

What is string fromCharCode ()?

The String. fromCharCode() method converts Unicode values to characters. The String. fromCharCode() is a static method of the String object. The syntax is always String.


2 Answers

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.

like image 86
Pointy Avatar answered Sep 21 '22 15:09

Pointy


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)

like image 35
ThiefMaster Avatar answered Sep 22 '22 15:09

ThiefMaster