0

Say i have the code:

function Obj(){
  var _x = 5;
  this.getX = function(){
    return _x;
  };
}

var obj = new Obj();

function God(){
  var x = obj.getX(); // i want 5 here
}

function Human(){
  var x = obj.getX(); // i want error/undefined here
}

var x = obj.getX(); // i want error/undefined here too

How can I hide the getX property from all objects except one?

mqklin
  • 1,928
  • 5
  • 21
  • 39
  • `from all objects except one` - Did you mean `all functions`? – thefourtheye May 15 '15 at 16:14
  • That doesn't make a lot of sense. Callees are usually unaware of their caller. If you need to identify the caller, then you have the caller pass an identification. In which case you also have to find a way to prevent callers to pass a fake ID. – Felix Kling May 15 '15 at 16:18

3 Answers3

4

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();
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • Nice. However, one would also have to prevent malicious actors to create an `Obj` with their own lock, and to have access to the original lock. *edit:* Yep :) – Felix Kling May 15 '15 at 16:22
0

Then add that method to one object only

see below example.

function  K(){ 
  this.name = 'Mr. K' 
}

var k1 = new K()

k1.getX = function() { 
  console.log(this.name) 
}
k1.getX(); // prints Mr.K

var k2 = new K()
k2.getX() // Error Uncaught TypeError: k2.getX is not a function
jad-panda
  • 2,509
  • 16
  • 22
0

One Way:
reference: How do you find out the caller function in JavaScript?

check for caller function name in Obj as referred in above post and take the appropriate action, but cannot be used in strict mode.

Community
  • 1
  • 1