Javascript找到原型链的开头

发布于 2024-08-20 20:09:35 字数 243 浏览 3 评论 0原文

如果我将一个函数设置为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╭⌒浅淡时光〆 2024-08-27 20:09:35

AFAIK 这是不可能的,因为对象就是对象,多个变量可以引用同一个对象,除非显式完成,否则不会将变量名称存储在对象上。

您当然可以使用 this 引用手头的对象,但是除非您执行类似的操作,否则您无法获取该变量。

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

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

names[0].alertName()

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()
狼性发作 2024-08-27 20:09:35

据我所知,不可能获得实际的对象名称(即变量名称)。

不过,您可以使用 this 来引用调用该函数的对象。

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

MyObject = {};
MyObject.MyFunc();
MyObject; // Object { foo = 'bar' }

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' }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文