thom
thom

Reputation: 51

Create a single object

I want to create a single object. Does the below code make sense?

singleObj = new function () {
    // act as a constructor.
};

Am I hurting any good practice?

I need a constructor. A simple object literal would not be useful here.

Upvotes: 2

Views: 1637

Answers (4)

zellio
zellio

Reputation: 32514

If you want just a single object, in that you are never going to make one again, an object literal works perfectly here.

var x = { };

Will give you an object. In order for

var F = function() {
};

to give you an object you will need to invoke F

var x = new F();

Upvotes: 1

The Internet
The Internet

Reputation: 8123

http://www.w3schools.com/js/js_objects.asp

//Used to create an object
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";

//Used as a constructor for the object
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
//how to declare objects via constructor template
var myFather=new person("John","Doe",50,"blue");
var myMother=new person("Sally","Rally",48,"green");

Upvotes: 0

Paul Perigny
Paul Perigny

Reputation: 973

Just create a new object and then populate it. You don't need a contrustor to do this.

var singleObject = {};
singleObject.value1 = "whatever";

If you really want to use a function, then you need to actually call it.

var singleObj = new (function () {
    // act as a constructor.
})();

We can use a self executing function by creating a anonymous function function(){}, and immediately calling it with an empty argument set.

Upvotes: 0

Warspawn
Warspawn

Reputation: 46

you could try someting like:

var objCreate = function() {
    var obj = {};
    // do constructor logic
    return obj;
};

Upvotes: 0

Related Questions