Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - object initializer?

Tags:

I've realized you can have a property in an object run automatically like this:

var obj = {      init:(function(){ alert('loaded');})();  } 

I'm trying to use this method as an initializer for the object. The problem I'm running into is passing a reference to 'obj' to the init property. I suspect it generates errors because the obj hasn't been completely built in browser yet. I'm trying to do the following, but unsuccessfully. If there's a way to do this, I'd love to know how.

var obj = {     prop:function(){ alert('This just ran.'); },     init:(function(){ obj.prop(); })(); } 
like image 805
Geuis Avatar asked Mar 08 '09 12:03

Geuis


People also ask

What is object initializer in JavaScript?

An object initializer is an expression that allow us to initialize a newly created object. It is a comma-separated list of zero or more pairs of property names and associated values of an object enclosed in a pair of curly braces {}.

What is object initialization?

An object initializer is an expression that describes the initialization of an Object . Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.

What is object initializer syntax?

The object initializers syntax allows you to create an instance, and after that it assigns the newly created object, with its assigned properties, to the variable in the assignment. Starting with C# 6, object initializers can set indexers, in addition to assigning fields and properties.

What is object literal notation of JavaScript?

In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions. Here's a snippet of an object literal with one property and one function. var greeting = {


2 Answers

If you want to create multiple instances of similar objects, you should use plain old constructor functions (remember to put shared properties in the prototype!).

If you want to create a single object, consider using an anonymous constructor. Your example would read:

var obj = new (function() {     this.prop = function() {         alert('This just ran.');     }      // init code goes here:     this.prop(); }); 

This has an additional benefit over object literals: the constructor function can be used as a closure over 'private' variables.

Don't overuse object literals: they may make simple things simple, but complex things will get overly complicated.

like image 132
Christoph Avatar answered Oct 17 '22 00:10

Christoph


This is not possible: obj doesn't exist until the whole block is interpreted.

like image 36
Maurice Perry Avatar answered Oct 17 '22 01:10

Maurice Perry