Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - why is declared function invoked at runtime

The mere declaration of a function to an object leads to its invocation

var a  = {};
a.xyz = new function() { 
    alert("dosomething");
}

I would expect, that the declared function a.xyz only gets invoked when I call it:
a.xyz();

What is wrong with my assumption?

like image 649
Lokomotywa Avatar asked Sep 14 '14 13:09

Lokomotywa


People also ask

Why JavaScript immediately invoked function expression?

Immediately invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.

What is the point of IIFE?

An Immediately-invoked Function Expression (IIFE for friends) is a way to execute functions immediately, as soon as they are created. IIFEs are very useful because they don't pollute the global object, and they are a simple way to isolate variables declarations.

Does JavaScript run top to bottom?

In interpreted languages, the code is run from top to bottom and the result of running the code is immediately returned. You don't have to transform the code into a different form before the browser runs it.

Which of the following executes immediately on creation?

This is called IIFE (Immediately Invoked Function Expression). One of the famous JavaScript design patterns, it is the heart and soul of the modern day Module pattern. As the name suggests it executes immediately after it is created.


2 Answers

Remove new and everything will be fine:

var a  = {};
a.xyz = function() { 
    alert("dosomething");
}

JSFiddle: http://jsfiddle.net/vnj8pzm1/

EDIT: More about IIFE - Immediately-Invoked Function Expression (IIFE)

like image 177
Hristo Enev Avatar answered Oct 20 '22 00:10

Hristo Enev


When you put new in front of your function definition, your function is being called as a constructor immediately.

As iceless mentioned, you should not have new in front of your function defintion. However, what iceless mentioned in the comment is incorrect

new function() {} or new function() {}(); will invoke the function just like function() {}(); or (function() {}());

new function() {} will create a new instance of an anonymous type, so in your code a.xyz is an object

if you change it to just function(){}() it would execute the function immediately and return nothing. See http://jsfiddle.net/mendesjuan/kzhg9ggu/

like image 45
Juan Mendes Avatar answered Oct 20 '22 01:10

Juan Mendes