views:

76

answers:

3
// JavaScript JSON
var myCode = 
{
   message : "Hello World",

   helloWorld : function()
   {
     alert(this.message);
   }
};
myCode.helloWorld();

The above JavaScript code will alert 'undefined'.

To make it work for real the code would need to look like the following... (note the literal path to myCode.message)

// JavaScript JSON
var myCode = 
{
   message : "Hello World",

   helloWorld : function()
   {
     alert(myCode.message);
   }
};
myCode.helloWorld();

My question is... if I declare functions using json in this way, is there some "relative" way to get access to myCode.message or is it only possible to do so using the literal namespace path myCode.message?

+3  A: 

Your first example works, the this value inside the helloWorld function will refer to the myCode object itself, because you invoked it by myCode.helloWorld();

When you invoke a function that is member of an object, this object will be set as the this value of the function.

In this case myCode is the base object of the myCode.helloWorld reference.

There are two more cases about how the this keyword is implicitly, for example, when you call a function that is not bound as property of any object, i.e.:

myFunc();

The this value inside myFunc will point to the global object.

When you use the new operator:

var obj = new MyFunc();

The this value inside MyFunc will refer to a newly created object.

And you can set the this value of a function explicitly, using call or apply:

function test () {
  return this + " World";
}
test.call("Hello"); // "Hello World"

Just a note, that's not JSON, JSON is simply a data interchange format, its grammar differs with the JavaScript Object Literal syntax, for example:

{ foo: "bar" }

The above is a valid JavaScript object literal, but is not valid JSON, JSON requires the property identifiers to be wrapped between quotes, and it has a limited set of data types allowed, for example, you cannot have functions as members of a JSON object.

CMS
A: 
Peter Bailey
No, `this` refers to the global object only when there is no *base object* in the reference being invoked, for example, `myFunc();`. In his example, the base object is `myCode` and it works, `myCode.helloWorld.call( myCode );` is redundant.
CMS
What CMS said..
Tim Down
That's what I get for posting after 3 beers. ¡Feliz Cinco de Mayo!
Peter Bailey
A: 

CMS hit the nail on the head, if you want more info you could check out http://www.scottlogic.co.uk/blog/chris/2010/05/what-is-this/

Chris