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?

1 Answer 1

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');
Sign up to request clarification or add additional context in comments.

1 Comment

thanks your trick really work, may be for now i will use this, i wish i can create prettier code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.