News for hackers. Stuff that matters.
Re:An Introduction to JavaScript's "this" by Bluem00 on Saturday September 26, 2009 @10:17PM (#846416)
This article does a good job of explaining a concept I had trouble with when first using javascript. Now, I usually use the approach recommended in the article of setting a private variable (e.g. self, or my) to the current value of 'this' in a javascript class.

However, I think the article is slightly incorrect on one minor point. It states, "this wants to be window whenever possible, which is not always what you want." I believe the correct description is: the 'this' variable in a function called in response to an event on dom object is set to that dom object. For the example given in the article, this is set to the window object because setTimeout causes an event on window to fire, not because there's any inherent preference for the window object.

Re:An Introduction to JavaScript's "this" by aboodman on Saturday September 26, 2009 @10:41PM (#846436)
There is indeed a preference for window (really the global) object. Try these:

<script> alert(this == window); function foo() { alert(this == window); } foo(); </script>

|this| is basically a magical variable that by default is set to the global object, but can also be set by the caller of a function one of two ways:

a) by setting a reference to the function on an object, and calling it with object or bracket notation: var someObj = {}; someObj.f = theFunction; someObj.f(); // now |this| inside theFunction will // point to someObj someObj["f"](); // same thing

b) by using apply: theFunction.apply(someObj);

You are right that in the case of event handlers, it is common in the DOM for event handlers to get their |this| set to the DOM node that fired the event. Since the default value of |this| is the global object, it isn't possible in the case of setTimeout for us to tell whether the caller (the host) explicitly set it, or if the function is being called without any value set for |this|.

Basically, |this| is an extra parameter to any function. It is controlled by the caller, and as such, should either be documented as part of the signature of the function, or else should not be relied on by the implementation of the function.

The common misunderstanding with people new to JS is that they expect |this| to be controlled by the callee, like it is in lots of other popular languages, and are surprised when calling convention can change its value.

Re:An Introduction to JavaScript's "this" by aboodman on Saturday September 26, 2009 @10:43PM (#846439)
BTW, imo, the behavior of |this| is a really unfortunate design flaw of JS. The amount of time that must have been spent learning and teaching this edge case over and over to every person new to the language is ... well, it's big.
Re:An Introduction to JavaScript's "this" by vicaya on Saturday September 26, 2009 @11:37PM (#846493)
The behavior of 'this' is from DOM bindings and not from the language per se. Javascript can set 'this' of any calling context to any object with 'apply' or 'call'. The convention for on* handlers is that 'this' is set to the DOM element when the handlers are called. I only learned to appreciate this, when I wrote my own little JS DOM framework a la JQuery or Dojo.
Re:An Introduction to JavaScript's "this" by litewulf on Sunday September 27, 2009 @02:45AM (#846604)
I believe actually that 'this' points to the global object.

So if there is no obvious thing for this to point at, it'll point at the global object. Its just implementation detail that in browsers it points to the window object.

Re:An Introduction to JavaScript's "this" by Bluem00 on Saturday September 26, 2009 @11:37PM (#846492)
Do you know why it was designed this way? Was 'new' added to javascript after the behavior of 'this' was already well defined and the creators did not feel comfortable changing it?
Re:An Introduction to JavaScript's "this" by jmtulloss on Sunday September 27, 2009 @06:36AM (#846745)
actually, no. As I understand it, the language was supposed to be some sort of weird conglomeration between traditional object oriented languages and dynamic, lisp-ish languages. The problem was that the creators had about 30 seconds to get this done and they could make things look more "normal" by not explicitly supporting every feature they envisioned.

"new", I believe, is actually an ancient relic of the prototypal class system. That's another topic entirely, but it's incredibly cool. Check out Douglas Crockford's articles on inheritance if you want closure on the issue. He has written way more than I have on the topic.

Re:An Introduction to JavaScript's "this" by praptak on Sunday September 27, 2009 @10:41AM (#846883)
"new", I believe, is actually an ancient relic of the prototypal class system.

I believe it is quite the opposite. It was a failed attempt to make the prototype-based object system look like class-based one. I vaguely remember reading this opinion in Crockford's "Javascript:The Good Parts" book.

Re:An Introduction to JavaScript's "this" by jmtulloss on Sunday September 27, 2009 @03:34PM (#847165)
Agreed. That's actually what I was trying to say. It's an ancient relic of JavaScript's implementation of the class system.
Re:An Introduction to JavaScript's "this" by jmtulloss on Saturday September 26, 2009 @10:43PM (#846438)
That was a bit inexact. It's kind of a hard point to generalize, I gave it another go.
Re:An Introduction to JavaScript's "this" by Bluem00 on Saturday September 26, 2009 @11:28PM (#846479)
Aboodman seems to have a better handle on it than I do. I think what I said about the dom object is correct, but he point out that window is the default value of this for other function calls.
Re:An Introduction to JavaScript's "this" by mhansen on Saturday September 26, 2009 @09:50PM (#846392)
The way I remember it: this is whatever is before the dot when you call the function.

E.g. for car.drive(); in the drive function, any reference to 'this' will get 'car'. If the function is called on it's own, as in 'drive()', 'this' will refer to the Global object (bad)

It's also possible to change 'this' by using the Function.prototype.apply() method, which allows you to pass a 'context' parameter that will become 'this'.

Re:An Introduction to JavaScript's "this" by kwamenum86 on Sunday September 27, 2009 @03:30AM (#846636)
The function: setTimeout(30, function() { myHotDog.getCondiments.apply(myHotDog); });

can actually just be: setTimeout(30, function() { myHotDog.getCondiments(); });

apply is definitely useful but it just makes the code more verbose in this case.

Re:An Introduction to JavaScript's "this" by nixy on Sunday September 27, 2009 @04:17AM (#846672)
Which JS engine allows you to call setTimeout like that? Isn't setTimeout(expression, timeInMs [, args]) the right way to go?
Re:An Introduction to JavaScript's "this" by bouncingsoul on Sunday September 27, 2009 @04:41AM (#846689)
That's correct, but the optional args parameter isn't supported in IE. So if you want to use setTimeout or setInterval to call a function with arguments you have to do it as an anonymous function with your function call inside.

You're right though that milliseconds should be the second argument, not the first.

https://developer.mozilla.org/En/Window.setTimeout

Re:An Introduction to JavaScript's "this" by kwamenum86 on Sunday September 27, 2009 @04:38PM (#847232)
Yes my mistake. milliseconds is the first argument. I just copied the function text verbatim. My real point was that you don't need to use apply in this context,, as the author implied.
Re:An Introduction to JavaScript's "this" by judofyr on Saturday September 26, 2009 @10:03PM (#846400)
Is this supposed to be Ruby?

    class HotDog:
         condiments
         def getCondiments
              return @condiments // @ is a reference to the current instance of HotDog.
         end
    end
Re:An Introduction to JavaScript's "this" by jmtulloss on Saturday September 26, 2009 @10:40PM (#846433)
sorry, that was typed up pretty quickly, and I'm not a rubyist... care to correct it?
Re:An Introduction to JavaScript's "this" by jhancock on Saturday September 26, 2009 @11:35PM (#846490)

  class HotDog
         @condiments
         def getCondiments
              return @condiments // @condiments is an instance variable of an instance of HotDog
         end
    end
note the mod to both the ivar def and the comment. You also do not need the initial ivar "definition" as ruby defines them on the fly when they are first referenced.
Re:An Introduction to JavaScript's "this" by xtho on Sunday September 27, 2009 @12:51AM (#846540)
No,

The first @condiments would define a class variable.

    class HotDog
        attr_accessor :condiments
    end
Or for Java-socialized folks:

    class HotDog
         def initialize
             @condiments = nil
         end

         def getCondiments
              return @condiments
         end
    end
Re:An Introduction to JavaScript's "this" by jhancock on Sunday September 27, 2009 @02:48AM (#846606)
oops, sorry. yes, the first line would define a "class instance" variable.

btw, I didn't show the attr_accessor meta-programming sine it hides the guts of the excercise.

Re:An Introduction to JavaScript's "this" by jmtulloss on Sunday September 27, 2009 @06:46AM (#846748)
I made some corrections. How's it look now?
Re:An Introduction to JavaScript's "this" by jhancock on Sunday September 27, 2009 @04:08PM (#847203)
I posted a bit too quick and too late at night. See corrections on this thread.
Re:An Introduction to JavaScript's "this" by axod on Sunday September 27, 2009 @04:24AM (#846679)
It's not a quirk, it doesn't need "fixing". Get a good javascript book. Still surprising how many people try to learn js by feeling around in the dark or by googling.
Re:An Introduction to JavaScript's "this" by jmtulloss on Sunday September 27, 2009 @05:12AM (#846707)
I absolutely agree. I tried to put "fixing" in quotes as much as possible. However, you have to see that for many programmers, it is unexpected behavior. In the eyes of many UI specialists, unexpected behavior is the definition of a quirk. JS fanatics have to be accepting of the fact that JS is not a regular language that follows "regular" rules.
Re:An Introduction to JavaScript's "this" by axod on Sunday September 27, 2009 @07:13AM (#846756)
Sure, I agree... And if you go in #javascript on freenode for a few minutes, you'll see endless questions about why their event handler doesn't work. Endless answers "use a closure".

I just wish people would read a book on the language first, then the behavior would be pretty obvious and expected.

Re:An Introduction to JavaScript's "this" by trjordan on Sunday September 27, 2009 @12:57AM (#846544)
Does anybody have a mirror? It appears to be down for me.
Re:An Introduction to JavaScript's "this" by _ck_ on Sunday September 27, 2009 @01:57AM (#846582)
Re:An Introduction to JavaScript's "this" by diN0bot on Sunday September 27, 2009 @02:35PM (#847106)
one neat way to define a class is like so:

  function MyClass(a, b) {
	// use this function as an instance constructor
	// eg, var m = new MyClass('foo', 'bar');
	this.a = a;
	this.b = b;
  }
  MyClass.prototype = {};
  _extend(MyClass.prototype, {
	instanceMethod: function() {
		...
	},
	...
  });
Re:An Introduction to JavaScript's "this" by volida on Sunday September 27, 2009 @10:45AM (#846889)
This article is wrong. You need to use prototype when defining your functions.

Here is how to do it:

  <html>
  <head>
  <script>

  function HotDog () {
	this.name=arguments[0];
  } 

  HotDog.prototype.name=null;

  HotDog.prototype.getCondiments= function () { 
	document.getElementById('test').innerHTML='started...'  +this.name;
  };
  var myHotDog = new HotDog('test 001');

  window.onload= function() {
	setTimeout(30, myHotDog.getCondiments());
  };

  </script>

  </head>
  <body>
  <div id=test>loading...</div>
  </body>
  </html>
Re:An Introduction to JavaScript's "this" by Bluem00 on Sunday September 27, 2009 @11:12AM (#846903)
While you can use prototype, why do you need to? What specifically do you mean by "the article is wrong?"
Re:An Introduction to JavaScript's "this" by volida on Sunday September 27, 2009 @02:39PM (#847111)
if you dont use prototype the function will not belong το the new object you create, therefore you will not be able το call the function from settimeout, which was the problem the author assumed το have.
Re:An Introduction to JavaScript's "this" by DougBTX on Sunday September 27, 2009 @04:12PM (#847205)
Try extending the time on your timeout in the example, say to 30000 milliseconds. You might get a surprise when you see your function get called immediatley.

In the article, you are right that he should use prototype, but not for the reason you mention. In the example, he does this.foo = function, so the function does get associated with the object. The problem is that the function gets recreated every time the HotDog constrictor gets called. Better to put getCondiments on the prototype, so that it is only defined once.

Re:An Introduction to JavaScript's "this" by volida on Sunday September 27, 2009 @09:01PM (#847479)
Sorry, I was typing a bit fast. This should be ok.

  window.onload= function() {  
	setTimeout( "myHotDog.getCondiments();", 3000);
  };
Re:An Introduction to JavaScript's "this" by jmtulloss on Sunday September 27, 2009 @03:37PM (#847170)
I would never not use a prototype in production code, but prototypes are a different topic that I wanted to avoid for this article. I'm just trying to explain "this".

Also, your code isn't right. You're calling myHotDog.getCondiments instead of passing a reference to setTimeout.

Re:An Introduction to JavaScript's "this" by volida on Sunday September 27, 2009 @09:00PM (#847478)
Sorry, I wasn't clear enough. I didn't mean what you are explaining is wrong.