什么时候*不*在内置插件上使用新工作? [英] When does *not* using new work on built-ins?

查看:97
本文介绍了什么时候*不*在内置插件上使用新工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用内置的JavaScript对象和构造函数,我发现有点奇怪。

Playing with built-in JavaScript objects and constructors, I noticed something a little odd.

有时,通过调用没有<$的构造函数可以获得新对象C $ C>新。例如:

Sometimes, it's possible to get new objects by calling a constructor without new. For example:

> new Array(1,2,3,4)
[1, 2, 3, 4]
> Array(1,2,3,4)
[1, 2, 3, 4]

但有时这不起作用:

> Date()
"Thu Jun 05 2014 00:28:10 GMT-0600 (CST)"
> new Date()
Date 2014-06-05T06:28:10.876Z

是在ECMAScript规范中的任何地方定义的非新构造函数内置函数的行为?请注意,此行为实际上很有用;我可以通过调用 Array.apply(arr)来制作数组的非稀疏副本,但是如果它是跨平台的话,我只会觉得这样做很舒服。 / p>

Is the behavior of non-new constructor built-in functions defined anywhere in the ECMAScript specification? Note that this behavior is actually useful; I can make a non-sparse copy of an array by calling Array.apply(arr), but I'd only feel comfortable doing that if it were cross-platform.

推荐答案

本机方法的行为取决于EcmaScript规范。

The behaviour of a native method depends on the EcmaScript specification.

对于日期 规范说:


调用日期时作为函数而不是构造函数,
返回表示当前时间(UTC)的字符串。

When Date is called as a function rather than as a constructor, it returns a String representing the current time (UTC).

注意:函数调用Date(...) 不等同于具有相同参数的对象创建表达式new Date(...)。

NOTE : The function call Date(…) is not equivalent to the object creation expression new Date(…) with the same arguments.

数组 spec说


当Array作为函数而不是构造函数调用时,它是
创建并初始化一个新的Array对象。

When Array is called as a function rather than as a constructor, it creates and initialises a new Array object.

因此函数调用
Array(...) 等同于 到对象创建表达式new Array (...)
具有相同的参数。

Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.

那么无论是否使用 new它是如何工作的关键字完全取决于您使用的方法,以及在没有new关键字的情况下调用时应该发生的内容。

So how it works with or without the new keyword is completely dependant on what method you're using, and what the spec says should happen when called without the new keyword.

例如,Math对象再次不同

For instance, the Math object is different again


Math对象没有[[Construct]]内部属性;使用新的
运算符将Math对象用作构造函数是

The Math object does not have a [[Construct]] internal property; it is not possible to use the Math object as a constructor with the new operator.

这篇关于什么时候*不*在内置插件上使用新工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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