对象的构造函数名称为字符串。绝对可以确定? [英] An object's constructor name as a string. Can definitely be determined?

查看:85
本文介绍了对象的构造函数名称为字符串。绝对可以确定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我想知道一个对象的构造函数的名称是一个

字符串。这样的东西


< script type =" text / javascript">

function Foo(){};

var a = new Foo();

alert(''"''+

a.constructor.toString()。match(/ function\s * ([a-zA-Z \ $] [\\\\\] +)[^ \\\] \\)/)[1]

+''"'' );

< / script>

虽然这适用于IE,Opera,Firefox,Safari我不确定它

保证可以正常工作。


我在ECMA-262规范中查看了返回的字符串

Function.prototype.toString()in第15.2.4.2节。它表示

空格,行终止符和分号使用是依赖于实现

。我认为上面的正则表达式可以处理那些

的差异。


我担心的是他的规格说返回值有

形式的函数声明。这是否意味着返回的字符串

肯定会包含构造函数的名称?可以吗

返回类似于function(){}的东西?


谢谢,

Peter

Hi,

I want to know the name of an object''s constructor function as a
string. Something like this

<script type="text/javascript">
function Foo(){};
var a = new Foo();
alert(''"'' +
a.constructor.toString().match(/function\s*([a-zA-Z\$][\w\$]+)[^\w\$]/)[1]
+ ''"'');
</script>

Although this works in IE, Opera, Firefox, Safari I''m not sure that it
is guaranteed to work.

I looked in the ECMA-262 specs about the returned string for
Function.prototype.toString() in section 15.2.4.2. It says that the
whitespace, line terminators and semi-colon use are implementation
dependent. I think the above regular expression can handle those
difference.

What I''m worried about is that he specs say the return value has the
form of a "function declaration". Does that mean the returned string
will definitely contain the name of the constructor function? Could it
instead return something like just "function () {}"?

Thank you,
Peter

推荐答案

[\ w\


+)[^ \ w\
+)[^\w\


/)[1]

+''"'');

< / script>


虽然这适用于IE浏览器,Opera,Firefox,Safari我不确定它是否可以保证工作。


我在第15.2.4.2节中查看了关于返回字符串的ECMA-262规范

Function.prototype.toString()。它表示

空格,行终止符和分号使用是依赖于实现

。我认为上面的正则表达式可以处理那些

的差异。


我担心的是他的规格说返回值有

形式的函数声明。这是否意味着返回的字符串

肯定会包含构造函数的名称?可以吗

返回类似于function(){}的东西?


谢谢,

Peter

/)[1]
+ ''"'');
</script>

Although this works in IE, Opera, Firefox, Safari I''m not sure that it
is guaranteed to work.

I looked in the ECMA-262 specs about the returned string for
Function.prototype.toString() in section 15.2.4.2. It says that the
whitespace, line terminators and semi-colon use are implementation
dependent. I think the above regular expression can handle those
difference.

What I''m worried about is that he specs say the return value has the
form of a "function declaration". Does that mean the returned string
will definitely contain the name of the constructor function? Could it
instead return something like just "function () {}"?

Thank you,
Peter


这篇关于对象的构造函数名称为字符串。绝对可以确定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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