找出实例变量名称本身 [英] Find out instance variable name out of itself

查看:73
本文介绍了找出实例变量名称本身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  function MyClass(){
this.myProp ='';
}
MyClass.prototype.myTestFunction = function(){
alert('test');
}

现在,我们实例化这个类。

  var myTestInstance = new MyClass(); 
myTestInstance.myTestFunction();

这会输出一个警报'test'。



现在我希望将变量名'myTestInstance'放入函数'myTestFunction()'中,而不必将其作为参数传递。

是否有可能从被调用的函数中找出实例的变量名?



感谢您的帮助!



编辑:只是为了添加信息为什么我需要这个:我在我的真实项目中创建的每个实例都是一个特殊的HTML表格。在标题字段中是每列的排序按钮。因此,我动态地添加了一个链接元素 href ='javascript:myTableInstance.sort()'。要在实例中动态地打印它,我需要变量名称。



会有另一个更好的解决方案吗? h2_lin>解决方案

不,它没有任何意义。首先,实例不绑定到一个变量(它可能被很多变量引用,它可能被none引用 - 可能作为某个数组的成员) - 所以问题存储变量的名称是什么该实例无法回答。其次,myTestFunction和myTestInstance的范围可能会非常不同。在通常情况下,myTestFunction不会看到myTestInstance定义的范围 - 因此知道变量的名称将无济于事。



您应该只使用this在myTestFunction里面。

I've created a JavaScript Class just as following:

function MyClass() {
    this.myProp = '';
}
MyClass.prototype.myTestFunction = function() {
    alert('test');
}

Now, I instantiate this class.

var myTestInstance = new MyClass();
myTestInstance.myTestFunction();

This outputs an alert with 'test'.

Now I want to have the variable name 'myTestInstance' into the function 'myTestFunction()' without having to pass it as a parameter.

Is it somehow possible to find out the variable name of the instance from inside the called function?

Thank you for your help!

EDIT: Just to add information why I would need this: Every instance I create in my real project is a special HTML table. In the header fields are sort-buttons for every column. Therefore I added dynamically a link-element with href='javascript:myTableInstance.sort()'. To print this dynamically IN the instance, I needed the variable name.

Would there be another, better solution?

解决方案

No, it does not make sense in any way. First of all, instance is not tied to a single variable (it might be referenced by many variables, it could be referenced by none - perhaps as a member of some array) - so the question "what is the name of the variable that stores the instance" is unanswerable. Secondly, the scope of myTestFunction and myTestInstance could be very different. In a usual case myTestFunction would not "see" the scope that has myTestInstance defined - so knowing the name of the variable would not help.

You should just use "this" inside myTestFunction.

这篇关于找出实例变量名称本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆