JavaScript Objects

Hallo!

Because JavaScript is not object oriented, how do I create objects with constructors etc? In the end, I want me/others to be able to write

new ElectionTime_Stian.Party({
name: “Sandy Shores Hospital”,
id: 12341,
modifiers: [“Silly”, “Money”, “Action”]
})

Thanks in advance!

Don’t u dare Deutch me!
(and don’t anyone reply to this or Charlie will be mad)

1 Like

Ok, I wont reply.

1 Like

Thanks.

1 Like

I usually do something like this:

var MyNameSpace = MyNameSpace || {};

MyNameSpace.MyClass = function(bar){
	this.bar = bar;
};

(function(){
	var p = MyNameSpace.MyClass.prototype;
	
	p.foo = function(){
		return this.bar;
	};
})();

usage is:

var obj = new MyNameSpace.MyClass('test');
obj.foo();//returns 'test'

Aha, thanks Patrick!

But why the MyNameSpace || {}? Is this for assigning a value or something?

essentially a namespace is just a normal object that holds other objects in JS.

by saying MyNameSpace = MyNameSpace|| {}; you just say that if MyNameSpace is already defined, use the existing object, otherwise create a new empty object. This just prevents you from accidentally overriding an existing MyNameSpace definition.

I usually don’t do this but only because I make sure that I load files in a specific order so my namespace is guaranteed to be defined.

hope this helps.

Ok, thanks! I’ll play around with it a bit :slight_smile: