They are completely different. The first is what is called JSON, Javascript Object Notation, and assigns randomFunction to a new object with 2 attributes, both functions.
The second creates a function to call a second function.
If you are using PHP please use the [PHP] and [/PHP] forum tags for highlighting...
The same applies to HTML and the forums [HTML][/HTML] tags.
In case you don't understand why scragar keeps repeating that they're different, it is because the function is called from a global context, as shown in the last line of the last bit of code. As for the object, the object's declaration maps 'foo' to a function. You need to use the dot notation for objects to fetch the function mapped to 'foo', and add the parentheses to actually call the function.
Code:
var bar = 4;
var obj = {
foo: function() {
alert("This is a member function 'foo'. bar=" + bar + ", this.bar=" + this.bar);
},
bar: '"Hello, nurse!"'
};
function foo() {
alert("This is a global function 'foo'. bar=" + bar + ", this.bar=" + this.bar);
}
obj.foo(); //Call the 'foo' member function of 'obj'.
foo(); //Call the global function.
Notice the 'this.bar' stuff? Since foo() is a global function in the last case, 'this' refers to the scope of the function, which is the 'window' object. The first line of the script is actually 'window.bar', not just 'bar'. In the case of the function called as obj.foo() in my code, 'this' refers to the scope of the function again, which is the 'obj' object. This is why the result of alerting bar and this.bar is different in each function.
This is the biggest difference - the effect the function has based upon its scope and what the function is supposed to do as well as how it is meant to be used. Simply put, don't use an object when you don't need one.
Last edited by rpgfan3233; 02-16-2009 at 09:46 PM.
Bookmarks