为什么我们需要“新”产品?创建数组时使用关键字? [英] Why do we need the "new" keyword when creating an array?

查看:46
本文介绍了为什么我们需要“新”产品?创建数组时使用关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我问错了,但是我主要想知道创建带有和不带有 new关键字的数组有什么区别?何时合适?

Maybe I'm asking this incorrectly, but I'm primarily wondering what is the difference between creating an array with and without the "new" keyword? When is it appropriate to use?

var myPix = new Array("Images/pic1.jpg", "Images/pic2.jpg", "Images/pic3.jpg"); 

我知道 new关键字会创建一个新对象。但是,由于我正在创建一个保存数组对象的变量,因此不使用 new数组是否仍会创建?

I know that the the "new" keyword creates a new object. But, since I'm creating a variable that holds the array object, isn't the array still created without using "new"?

最后,我不能只是

var myPix = ["Images/pic1.jpg", "Images/pic2.jpg", "Images/pic3.jpg"];


推荐答案

在Javascript中,类实际上是它们自己的构造函数/ initializer函数。 Array 函数就是一个例子。当您调用 new Array 时,JavaScript首先创建一个未初始化的对象,然后使用该新对象调用 Array() 。如果运行 Array()而没有 new ,则将跳至第二步,而无需创建任何要初始化的对象

In Javascript, "classes" are really their own constructor/initializer functions. The Array function is an example. When you call new Array, Javascript first creates an uninitialized object, and then invokes Array() with that new object as this. If you run Array() without the new, you're skipping to that second step without creating any object to initialize.

借助其内置类型函数,如 Array ,Javascript会转身为您创建对象在没有 new 的情况下调用时;他们做正确的事,因为这样写。除非您竭尽所能地对它们进行编码,否则您自己的类型函数不会那么体贴。

With its built-in type functions like Array, Javascript will turn around and create the object for you even when called without new; they "do the right thing" because they're written that way. Your own type functions won't be so considerate unless you go out of your way to code them so.

通常,如果您要查找速记符号,则应使用方括号形式。

In general, if you're looking for shorthand notation, you should just use the bracket form.

这篇关于为什么我们需要“新”产品?创建数组时使用关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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