JavaScript:using constructor without operator'new' [英] JavaScript: using constructor without operator 'new'

查看:238
本文介绍了JavaScript:using constructor without operator'new'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我理解以下代码的工作原理:

Please help me to understand why the following code works:

<script>
    var re = RegExp('\\ba\\b') ;
    alert(re.test('a')) ;
    alert(re.test('ab')) ;
</script>

在第一行中没有 new 运算符。

In the first line there is no new operator.

据我所知, JavaScript 是一个函数,用于初始化由操作符 new 创建的对象,它们不会返回任何内容。

As far as I know, a contructor in JavaScript is a function that initialize objects created by the operator new and they are not meant to return anything.

推荐答案

一般来说,如果某些东西被记录为构造函数,请使用 new 但是在这种情况下, RegExp 有一个定义的工厂行为,你已经调用它作为一个函数的情况。请参阅ECMAScript(JavaScript)的第15.10.3节规范 (链接到传出规范;部分号在新规范中是相同的,您可以从ECMA下载首页 [右侧];我不想直接链接到〜4MB的PDF文件):

In general, if something is documented as being a constructor, use new with it. But in this case, RegExp has a defined "factory" behavior for the situation where you've called it as a function instead. See Section 15.10.3 of the ECMAScript (JavaScript) specification (that links to the outgoing spec; the section number is the same in the new spec, which you can download from the ECMA front page [on the right-hand side]; I don't want to directly link to a ~4MB PDF file):


15.10.3 RegExp构造函数作为函数调用

15.10.3.1 RegExp(模式,标志)

如果pattern是一个对象R,其[[Class]]属性为RegExp且flags未定义,则返回R不变。否则调用RegExp构造函数(15.10.4.1),传递pattern和flags参数并返回该构造函数构造的对象。

15.10.3 The RegExp Constructor Called as a Function
15.10.3.1 RegExp(pattern, flags)
If pattern is an object R whose [[Class]] property is "RegExp" and flags is undefined, then return R unchanged. Otherwise call the RegExp constructor (15.10.4.1), passing it the pattern and flags arguments and return the object constructed by that constructor.

你实际上可以定义自己的JavaScript构造函数,允许省略 new 关键字(通过检测它们被调用为函数,并转向并正确调用自己)但我不会建议它,因为它导致误导代码。

You can actually define your own JavaScript constructor functions to allow omitting the new keyword (by detecting they've been called as a function instead, and turning around and calling themselves correctly), but I wouldn't suggest it as it leads to misleading code.

这篇关于JavaScript:using constructor without operator'new'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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