javascript - a String.prototype's "this" doesn't return a string? -


what going on here? when thought knew js inside , out, gem comes up.

string.prototype.donothing = function() {   return this; };  alert(typeof 'foo'.donothing()) // object alert(typeof 'foo')             // string 

http://jsfiddle.net/djbmf/

this breaking things expect string, such jquery's .text(str) method.

here's thorough overview of this keyword. basically, javascript converts object, if wasn't one.

the following steps performed when control enters execution context function code contained in function object f, caller provided thisvalue, , caller provided argumentslist:

  1. if function code strict code, set thisbinding thisvalue.
  2. else if thisvalue null or undefined, set thisbinding global object.
  3. else if type(thisvalue) not object, set thisbinding toobject(thisvalue).
  4. else set thisbinding thisvalue

same thing happens numbers , booleans. similar donothing function return type of object.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -