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(); })(); }
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 {}.
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.
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.
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 = {
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.
This is not possible: obj doesn't exist until the whole block is interpreted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With