R
R
rimlin2014-06-30 14:21:34
JavaScript
rimlin, 2014-06-30 14:21:34

Why is there a double bracket for function expression?

Tell me why this code to execute alert ( Jsfiddle ):

var newclass = new Classname();
newclass.method.init();

function Classname () {
    this.method = function () {
        return {
            init: function () {
                alert();
            }
        }
    }()
}

And this code does not execute alert ( Jsfiddle ):
var newclass = new Classname();
newclass.method.init();

function Classname () {
    this.method = function () {
        return {
            init: function () {
                alert();
            }
        }
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Kirill, 2014-06-30
@rimlin

In the first case, it this.methodwill be the result of executing the function:

{
  init: function () {
    alert();
  }
}

And in the second - the function itself.

A
Alexey, 2014-06-30
@rdifb0

Look in the console, there will be a hint.
In the first case, the function will be executed immediately and the object will get into this.method. The second will contain a function that must first be called jsfiddle.net/G3ybH/3

4
4ikist, 2014-06-30
@4ikist

In the first case, encapsulation, in the second, no, in the second, init() must be called forcibly;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question