Reputation: 3936
Ok, I'm creating a constructor object within a closure(to hide it from other scripts that may conflict with it) for another function(this will become clear in a moment). Is there a way to add a reference of the caller function to the in-closed constructor:
// this can be located anywhere within a script
(function() {
function SomeConstructor(param) { this.param = param; }
SomeConstructor.prototype.doSomething = function(a) { this.param = a; return this; }
SomeConstructor.prototype.getParam = function() { return this.param }
// SomeConstructor.prototype.someFunct = ???
return function someFunct(param) {
if (param instanceof SomeConstructor) {
return param;
}
else if (param) {
return new SomeConstructor(param);
}
}
}());
the reason I need the reference is so I can chain between someFunct and it's constructed objects:
someFunct("A").doSomething("a").someFunct("B").doSomething("a").getParam();
Please note I need to retain the instanceof
check, so the following functions as specified:
// 1: The inner call creates a new instance of SomeConstructor
// 2: The 2nd(wrapping) call returns the inner calls instance
// instead of creating a new isntance
var a = someFunct(someFunct("b"));
Upvotes: 1
Views: 144
Reputation: 9538
Assign the function to the property of the prototype first and then return this property:
(function() {
function SomeConstructor(param) { this.param = param; }
SomeConstructor.prototype.doSomething = function(a) { this.param = a; return this; }
SomeConstructor.prototype.getParam = function() { return this.param }
SomeConstructor.prototype.someFunct = function someFunct(param) {
if (param) {
return new SomeConstructor(param);
}
}
return SomeConstructor.prototype.someFunct;
}());
Upvotes: 1