数组创建,为什么这样做?(Array creation, why does this work?)

编程入门 行业动态 更新时间:2024-10-25 16:21:10
数组创建,为什么这样做?(Array creation, why does this work?)

我理解为什么:

output = new Array();

output = [];

但为什么这样呢?

output = Array();

I understand why :

output = new Array();

and

output = [];

but why does this work?

output = Array();

最满意答案

简单地实现了Array()构造函数,因此不需要使用new调用它。 它是语义定义的一部分。

像Array()这样的内置构造函数(可能)不是用JavaScript编写的,但是你可以在自己的代码中获得相同的效果:

function MyConstructor() { "use strict"; var newObj = this || {}; // ... return newObj; }

当你用new调用时,构造函数会看到它有一些绑定到它的东西。 如果你不这样做,那么this将是未定义的(因为“use strict”;你可以检查this是否是全局对象,你必须为旧的IE做)。

构造函数的返回值不是new表达式的值 - 它始终是新创建的对象。 但是,当您在没有new情况下调用它时,将使用返回值。

编辑 - RobG在评论中指出,为了使其真正正常工作,函数创建的“合成” newObj需要明确设置,以便它有适当的原型等。这有点棘手; 代码简单地执行此操作可能是最简单的:

function MyConstructor() { "use strict"; if (!this) return new MyConstructor(); // ... or possibly using "apply" if you need parameters too }

TJ Crowder在这里就对象/继承争论的主题写了一些很棒的答案。

The Array() constructor is simply implemented such that calling it with new is unnecessary. It's part of its semantic definition.

Built-in constructors like Array() are (probably) not written in JavaScript, but you can get the same effect in your own code:

function MyConstructor() { "use strict"; var newObj = this || {}; // ... return newObj; }

When you invoke with new, the constructor will see that's it's got something bound to this. If you don't, then this will be undefined (because of "use strict"; you could alternatively check to see whether this is the global object, which you'd have to do for old IE).

The return value from a constructor is not the value of a new expression - that's always the newly-created object. When you call it without new, however, the return value will be used.

edit — RobG points out in a comment that for this to really work properly, the "synthetic" newObj that the function creates needs to be explicitly set up so that it's got the proper prototype etc. That's kind-of tricky; it might be simplest for the code to simply do this:

function MyConstructor() { "use strict"; if (!this) return new MyConstructor(); // ... or possibly using "apply" if you need parameters too }

T.J. Crowder has written some awesome answers here on the subject of object/inheritance wrangling.

更多推荐

本文发布于:2023-08-05 20:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1439081.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:这样做   数组   Array   creation   work

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!