What is the difference between declaring javascrip

2019-06-17 08:44发布

问题:

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?

回答1:

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";


回答2:

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() {}



回答3:

The major difference between the two is that one variable is local and the other is global. “var” basically defines the scope of the variable.

When we add var to a variable value assignment, javascript ensures that the variable is confined to whichever function it is assigned to and does not collide with the same name variable within another function.

When we don’t use var, then it is declared as a global function and chances of collision can happen. So it’s always advisable to use “var” before variable value assignment. If needed use an anonymous function for closure.