1

I need to know who call a function, for example i have code like this :

var observe = function(newvalue, callback) {
      console.log('who call me?');
      callback('new value is ' + newvalue);
}

var ViewModel = function() {
  var self = this;
  self.Id = '1';
  self.Name = observe;
  self.NickName = observe;
  self.someFunction = function() {
    return 1 + 2;
  }
}
var vm = new ViewModel();

vm.NickName('test', function(resp) {
  console.log(resp);
})

For this example, in observe i need the code know who call it is vm.NickName or NickName.

How to trick this problem with pure javascript?

yozawiratama
  • 4,209
  • 12
  • 58
  • 106

1 Answers1

2

From within a function, you cannot determine what reference was used to call it. If you want to do that, you need to create separate functions (which can then call the central one), or pass it an argument that tells it how it's being called, etc.

For instance, this example passes it an argument:

var observe = function(who, newvalue, callback) {
      console.log('Called by: ' + who);
      callback('new value is ' + newvalue);
};

// ...

self.Name = observe.bind(self, 'Name');
self.NickName = observe.bind(self, 'NickName');
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875