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?
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.
Array doesn't have charCodeAt method.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With