简体   繁体   中英

How to find the object a function belongs to?

Given a function, is there a way to find out the object that holds it?

var dog = { 
  bark: function() { alert('dfd') },
  name: 'Bill'
}

function getNameFromBark(barkFunc){
   //How to implement this method?
}

getNameFromBack(dog.bark); //I would like this to return Bill.

Why not just dog.name ?

Functions can be bound to an object. It can access the properties of that object using the this keyword. You can rebind functions with the bind function, which changes the value of this .

There is no way that I know of to ask a function what it is bound to.

like:

var my_func = dog.bark; // removing `dog` from the reference
my_func.getBoundObject().name; // would return Bill

Seems like you could use prototypes here:

function Dog(name) {
  this.name = name;
}

Dog.prototype = {

  getName: function() {
    return this.name;
  },

  bark: function() {
    alert('dfd');
  }

};

var dog = new Dog('Bill');
console.log(dog.getName()); //=> 'Bill'

The way you've written your code, dog.bark is just a function reference and has no association with any specific object once you've passed it as dog.bark so there is no way to get any other data from the object when you just pass it like this:

getNameFromBark(dog.bark);

Inside of getNameFromBack() , the passed argument is just a function. Methods in javascript are just properties on an object and once you retrieve the property value, it's just a function. There is no object reference associated with the function itself. So short of just using dog.name to reference the global object dog , you can't get dog.name from within that function any other way.


Now, you could restructure you code any number of ways to allow that. For example, you could pass the object instead of the function:

getNameFromBark(dog);

And, then inside of getNameFromBark() , you can access the .name property from the passed in object.


Or, in a bit of an abuse of the object system, you could put a property on the function itself that contains the name:

var dog = { 
  bark: function() { alert('dfd') },
  name: 'Bill'
}

// assign name property to the bark function too
dog.bark.name = dog.name;

function getNameFromBark(barkFunc){
   //How to implement this method?
   return(barkFunc.name);
}

getNameFromBack(dog.bark); //I would like this to return Bill.

But, this is probably not the best way to design your code. If we understood the real problem you were trying to solve, we could probably suggest a much better object-oriented architecture that doesn't duplicate properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM