I have function-constructor. I want to control what function (object) can call it. Here’e the example:
function Bar() {
// foo can be created only here, when Bar is instantiated
var foo = new Foo();
}
function Foo() {
// I'd like to have something like this here:
if (caller != Bar) {
alert("Not allowed, the caller is not Bar");
return;
}
}
var bar = new Bar(); // this is correct, Foo can be created inside Bar
var foo = new Foo(); // prints "Not allowed, the caller is not Bar" and exits
Is it possible to implement in JS? Are there some functions for such kind of control?
What will be created from Foo if the creation will be aborted this way?
You can’t reliably identify the caller in a constructor across browsers, particularly in the new strict mode.
Instead, you can define
Foo()inside ofBar()or define them both inside of the same self executing function so thatFoo()is not known outside the scope ofBar()and can thus only be created there.Some examples:
You may find this article instructional which discusses various ways of making instance data truly private: http://www.crockford.com/javascript/private.html. It’s not exactly the same as what you’re asking here, but uses some of the same techniques (hiding private data in a closure).