Javascript找到原型链的开头
如果我将一个函数设置为 Object.prototype,并尝试从对象 Foo 调用该函数,该函数是否有办法知道最初调用它的对象是什么?
Object.prototype.MyFunc = function () {
console.log("I was called by " + (//object name here...));
}
Foo = {};
Foo.MyFunc();
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
AFAIK 这是不可能的,因为对象就是对象,多个变量可以引用同一个对象,除非显式完成,否则不会将变量名称存储在对象上。
您当然可以使用
this
引用手头的对象,但是除非您执行类似的操作,否则您无法获取该变量。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..据我所知,不可能获得实际的对象名称(即变量名称)。
不过,您可以使用
this
来引用调用该函数的对象。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
.