views:

41

answers:

2

If I set a function to Object.prototype, and try to call the function from object Foo, is there a way for the function to know what object originally called it?

Object.prototype.MyFunc = function () {
    console.log("I was called by " + (//object name here...));
}

Foo = {};
Foo.MyFunc();

Thanks!

A: 

As far as I know, it’s not possible to get the actual object name (i.e. var name).

You can however refer to the object the function was invoked upon by using this.

Object.prototype.MyFunc = function() {
 this.foo = 'bar';
}

MyObject = {};
MyObject.MyFunc();
MyObject; // Object { foo = 'bar' }
Mathias Bynens
+1  A: 

AFAIK it's impossible because objects are objects, multiple variables can refer to the same object, no variable name is stored on the object unless done explicitly.

You can of course refer to the object at hand with this but you can't get the variable unless you did something like..

Object.prototype.alertName = function() {
    alert( this.name )
}

var names = [
  {name:'John'}
];

names[0].alertName()
meder