I'm a confused newbie. I read in a tutorial that you create a javascript object like so:
function myObject() {
this.myProperty = "a string";
this.myMethod = function () {
//Method code
}
}
Then I read somewhere else that you create an object like so:
var myObject = {
myProperty: "a string",
myMethod : function () {
//Method code
}
}
What is the (non-subjective) difference between the two? Is there an official right way and a wrong way?
Both declarations are correct but they have different semantics.
The first type of declaration allows you to create instances of your objects:
var t = new myObject();
// then use t
t.myProperty = "some value";
var otherT = new myObject();
otherT.myProperty = "some other value";
The second is almost like a static object:
myObject.myProperty = "some value";
Here is a direct comparison...
function myObject() {
This declares the function when JavaScript is parsed...
var myObject = function () {
This declares the function at run time.
If you use the "var" method, your function must be declared before you use it... try this example.
myFunction(); // Works
myVarFunction(); // Boom
var myVarFunction = function () { alert("Hi"); };
function myFunction() { alert("Hi"); };
So why use the "var" method if you have to be more careful to use it? It is all to do with the scope... scoped functions are considered better.
UPDATE: And there are some great explanations here:
var functionName = function() {} vs function functionName() {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With