Assuming you're using God
and Human
as objects via new God
and new Human
, you can use a lock and key to allow the function to be accessed with the correct type:
function Obj(lock) {
var _x = 5;
this.getX = function (key) {
if (key instanceof lock) {
return _x;
}
};
}
function God() {
var x = obj.getX(this);
console.log(x);
}
function Human() {
var x = obj.getX(this);
console.log(x);
}
var obj = new Obj(God);
var g = new God(); // logs 5
var h = new Human(); // logs undefined
Of course, one could always pick the lock:
function Thief() {
var g = new God();
var x = obj.getX(g);
}
var t = new Thief(); // logs 5
Another approach to this lock & key mechanism is via a shared secret:
function Obj(lock) {
var _x = 5;
this.getX = function (key) {
if (lock === key) {
return _x;
}
};
}
(function (scope) {
//When I wrote this, only God and I understood what I was doing
//Now, God only knows
var secret = {};
scope.God = function () {
var x = scope.obj.getX(secret);
console.log(x);
};
scope.obj = new Obj(secret);
}(window));
function Human() {
var x = obj.getX();
console.log(x);
}
var g = new God();
var h = new Human();