On 8 December 2011 07:30, Jake Verbaten <[email protected]> wrote:

> It would be great if people didn't answer with _completely_ wrong
> solutions.
>
> Before you recommend an answer please run it in a JavaScript console to
> check it works.
>
> As an aside to those who said `this.a` it may time you learned how `this`
> actually works.
>
>
I agree, but no need to be *quite* so snarky!

To explain: `this` is set inside function calls (a) when they are called as
a method, (b) when they are called with .call or .apply, and (c) when
called with new. Inside an object literal, this is the this of the outer
function, not the object.

Here's an example:

function makeAnObject() {
    var outerThis = this;

    return {
      a: this,
      b: function () {
        return this;
      }
   };
}

When you call makeAnObject as a function, the `this` that `a` is set to is
the same as `outerThis` (which is the global object). The `this` inside `b`
will be the new object.

Nick
-- 
Nick Morgan
http://skilldrick.co.uk
@skilldrick

Save our in-boxes! http://emailcharter.org

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to