开发者

Javascript find beginning of prototype chain

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 ori开发者_JAVA技巧ginally called it?

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

Foo = {};
Foo.MyFunc();

Thanks!


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()


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' }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜