My end goal is being able to do something like this:
MyVar(parameter).functionToPerform();
Silly enough, even after reading up on how varia
jQuery()
is both a module with global methods, and a constructor. It automatically calls a constructor if it needs to. If we are not called with a new
keyword, then this
will not have been constructed with MyClass
. We can detect that and call the function in constructor mode instead. Once we do that, then this
will be an instance of MyClass
and we can start adding stuff to it.
var MyClass = function(context) {
// if the function is called without being called as a constructor,
// then call as a constructor for us.
if (this.__proto__.constructor !== MyClass) {
return new MyClass(context);
}
// Save the context
this.context = context;
// methods...
this.print = function() {
return "Printing";
}
this.move = function() {
return this.context;
}
};
$('#output').append('- print(): '+ MyClass().print() +'
');
$('#output').append('- move():'+ MyClass('azerty').move() +'
');
$('#output').append('- context: '+ MyClass('azerty').context +'
');
http://jsfiddle.net/rvvBr/1/