// 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?
Your first example works, the
thisvalue inside thehelloWorldfunction will refer to themyCodeobject itself, because you invoked it bymyCode.helloWorld();When you invoke a function that is member of an object, this object will be set as the
thisvalue of the function.In this case
myCodeis the base object of themyCode.helloWorldreference.There are two more cases about how the
thiskeyword is implicitly, for example, when you call a function that is not bound as property of any object, i.e.:The
thisvalue insidemyFuncwill point to the global object.When you use the
newoperator:The
thisvalue insideMyFuncwill refer to a newly created object.And you can set the
thisvalue of a function explicitly, usingcallorapply: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:
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.