开发者

What is the difference between declaring javascript objects with var vs. with function?

开发者 https://www.devze.com 2023-01-20 09:47 出处:网络
I\'m a confused newbie.I read in a tutorial that you create a javascript object like so: function myObject() {

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 lik开发者_如何学Goe 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() {}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消