Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  99] [ 2]  / answers: 1 / hits: 20984  / 14 Years ago, mon, february 28, 2011, 12:00:00

What is going on here? Just when I thought I knew JS inside and out, this gem comes up.



String.prototype.doNothing = function() {
return this;
};

alert(typeof 'foo'.doNothing()) // object
alert(typeof 'foo') // string


http://jsfiddle.net/dJBmf/



This is breaking some things that expect a string, such as jQuery's .text(str) method.


More From » javascript

 Answers
22

Here's a thorough overview of the this keyword. Basically, JavaScript converts it into an object, if it wasn't one.




The following steps are performed when
control enters the execution context
for function code contained in
function object F, a caller provided
thisValue, and a caller provided
argumentsList:




  1. If the function code is strict code, set the ThisBinding to
    thisValue.

  2. Else if thisValue is null or undefined, set the ThisBinding to the
    global object.

  3. Else if Type(thisValue) is not Object, set the ThisBinding to
    ToObject(thisValue).

  4. Else set the ThisBinding to thisValue




Same thing happens to Numbers and Booleans. A similar DoNothing function would return a type of object.


[#93529] Sunday, February 27, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
estefanib

Total Points: 508
Total Questions: 104
Total Answers: 83

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
;