Closures in auto executing functions vs objects

2020-02-03 06:29发布

Let us say I have the following:

var foo = (function(){
    var bar = 0;
    return {
       getBar: function(){
           return bar;
       },
       addOne: function(){
           bar++;
       },
       addRandom: function(rand){
           bar += rand;
       }
    }
})();

And I have the following:

var foo2 = function(){
    var bar = 0;
    this.getBar = function(){
           return bar;
       };
    this.addOne = function(){
           bar++;
       };
    this.addRandom = function(rand){
           bar += rand;
       }
};

Is the only difference in executing the functions a new?

alert(foo.getBar()); //0
foo.addOne();
foo.addRandom(32);
alert(foo.getBar()); //33

var foo2_obj = new foo2;
alert(foo2_obj.getBar());//0
foo2_obj.addOne();
foo2_obj.addRandom(32);
alert(foo2_obj.getBar());//33

They both out put the exact same thing.

So what is the difference in the long run?

What can one do that the other cannot?

Fiddle Demo of the above: http://jsfiddle.net/maniator/YtBpe/

7条回答
ゆ 、 Hurt°
2楼-- · 2020-02-03 07:14

The only difference is that foo will be a generic Object, whereas foo2_obj will identify as a foo2 when checking its type (i.e. foo2_obj.constructor == foo2 will be true, while the equivalent on foo is foo.constructor == Object).

Of course, there's an important distinction between foo and foo2 - foo is an object, while foo2 is a function (intended for use as a constructor). Thus, it is trivial to make as many instances of foo2 (of which foo2_obj is one), while the idea of creating "instances" of foo doesn't really make sense - the best you could do are copies (which is more difficult than calling a constructor).

Due to the copying/creating instances distinction, the second approach allows for real OO programming with prototype chains, while the first makes such things much more difficult (and ill-advised).

查看更多
地球回转人心会变
3楼-- · 2020-02-03 07:16

I think in my personal view of this two types
1- Singleton
2- Object

Let's we say we have one page having their javascript using Object (Second), and having many utils using singletons (First), and works fine.

But one day we need a new page that call the first page via AJAX, this new page have their javascript using Object (Second) and have the same utils using singleton, but we add some new functions in the utils singletons.

Turns out, the utils singletons in the new page are overriden for the loaded utils singletons in the first page, So when the new page execute some of those new function doesn't exist, generating errors ...

I think this is my point, the singletons are overriden when you have this scenario, and find erros in cases like this are hard.. hard..., diferent from a object that have unique instances

Cheers.

查看更多
闹够了就滚
4楼-- · 2020-02-03 07:19

[1]first,but not important:efficiency

function Foo1() {
    var bar = 0;
    return {
        getBar: function () {
            return bar;
        }
    }
}
var o = Foo1();
o.getBar();


function Foo2() {
    var bar = 0;
    this.getBar = function () {
        return bar;
    }
}
var o = new Foo2();
o.getBar();

which is the faster?,look object-literal-vs-new-operate

[2]program pattern:the former has no program pattern,but the latter will benefit form prototypal inheritance.if now we want to add a method named "logBar",

former:

1:extend every Foo1 instance:

o.logBar = function () {
    console.log(this.getBar());
}
o.logBar();

bad way!

2:find where Foo1 defined and add:

function Foo1() {
    var bar = 0;
    return {
        getBar: function () {
            return bar;
        },
        logBar:function () {
            console.log(this.getBar());
        }
    }
}
var o = Foo1();
o.logBar = o.logBar();

would you want to go back to do this when you want to add more method ervey time?

latter:

Foo2.prototype.logBar = function () {
    console.log(this.getBar());
}

var o = Foo2();
o.logBar = o.logBar();

this would be work fine.

[3] back to efficiency: in Foo1's way,it product logBar function instance ervey time when a Foo1 instance created.object-literal-vs-new-operate

查看更多
神经病院院长
5楼-- · 2020-02-03 07:20

foo and foo2_obj They are the same. In both cases you have a function that creates a new object, references a variable in closure scope and returns that object.

You have 4 things

  • anonymous function that is a factory for "foos"
  • object foo created from anonymous factory
  • foo2 which is a name factory for "foo2_objs"
  • object foo2_obj created from foo2 factory

The exact difference between using new and returning function literals from a function is neglible if you don't touch <Function>.prototype

You probably want to compare

var foo2 = function(){
    var bar = 0;
    this.getBar = function(){
           return bar;
       };
    this.addOne = function(){
           bar++;
       };
    this.addRandom = function(rand){
           bar += rand;
       };
};

To

var Foo = {
  addOne: function () { this.bar++; },
  addRandom: function (x) { this.bar+=x; }
};

var foo3 = function () {
  return Object.create(Foo, { bar: { value: 0 } });
}

foo3 uses prototypical OO. this means you don't have to recreate those functions all the time.

查看更多
Juvenile、少年°
6楼-- · 2020-02-03 07:22

The main difference is actually that foo is an object, whereas foo2 is a function.

That means that you'll not be able to create another object like foo that is not actually foo itself, except if you copy/paste its code.

On the other hand, you can create another foo2 object and manipulate it while using foo2_obj for another purpose.

To make short, foo is an instance while foo2 can bee seen as a class (even if it's just a function constructing an object).

It depends on what you want to do in your program, but I'd surely recommend to use the 2nd form which is allowing to reuse your code by creating other instances.

查看更多
何必那么认真
7楼-- · 2020-02-03 07:25

In the first one you can only create the object once, while with the second one you can create as many objects as you like. I.E. the first one is effectively a singleton.

Note that closures are not ok for the second one. Every time you instantiate it you are creating the functions all over again and waste a ton of memory. The prototype object is intended to counter this, where you can create the functions once outside a function scope and no accidental closures are created.

function foo2(){
    this._bar = 0;
}

foo2.prototype = {

    constructor: foo2,

    getBar: function(){
        return this._bar;
    },

    addOne: function(){
        this._bar++;
    },

    addRandom:function(rand){
        this._bar += rand;
    }

};

Then:

var a = new foo2, b = new foo2, c = new foo2;

Creates three instances which have their own _bar but share the same functionality.

jsperf

You can "compare" all of this to PHP, some of the code won't even run but it's "equivalent" in principle:


var foo = (function(){
    var bar = 0;
    return {
       getBar: function(){
           return bar;
       },
       addOne: function(){
           bar++;
       },
       addRandom: function(rand){
           bar += rand;
       }
    }
})();

is roughly "equivalent" to this in PHP:

$foo = new stdClass;

$foo->bar = 0;

$foo->getBar = function(){
    return $this->bar;
};

$foo->addOne = function(){
    $this->bar++;
}

$foo->addRandom = function($rand){
    $this->bar += $rand;
}

var foo2 = function(){
    var bar = 0;
    this.getBar = function(){
        return bar;
    };
    this.addOne = function(){
        bar++;
    };
    this.addRandom = function(rand){
        bar += rand;
    }
};

Is roughly "equivalent" to this in PHP:

Class foo2 {


    public function __construct(){
    $bar = 0;

        $this->getBar = function(){
            return $bar;
        };
        $this->addOne = function(){
            $bar++;
        };
        $this->addRandom = function($rand){
            $bar += rand;
        };


    }

}

function foo2(){
    this._bar = 0;
}

foo2.prototype = {

    constructor: foo2,

    getBar: function(){
        return this._bar;
    },

    addOne: function(){
        this._bar++;
    },

    addRandom:function(rand){
        this._bar += rand;
    }

};

Is roughly "equivalent" to this in PHP:

Class foo2 {

    public $_bar;

    public function __construct(){
        $this->_bar = 0;    
    }

    public function getBar(){
        return $this->_bar;    
    }

    public function addOne(){
        $this->_bar++
    }

    public function addRandom($rand){
        $this->_bar += $rand;
    }

}

...and is the only one that is close to OOP in the three above examples


查看更多
登录 后发表回答