What's the difference between Array(1) and new Array(1) in JavaScript?

前端 未结 3 1628
暗喜
暗喜 2020-12-01 04:33

I just started thinking about this, but couldn\'t get any differences to expose themselves whilst mucking around in jsFiddle.

var a = new Array(1),
    b = A         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 05:08

    The difference lies in the implementation of the Array function. Whether a call to Array without a new operator will return an instance of Array or not is implementation dependent. For example Mozilla's SpiderMonkey engine does this:

    static JSBool
    Array(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
    {
         jsuint length;
         jsval *vector;
    
         /* If called without new, replace obj with a new Array object. */
    

    That is an actual comment from the actual source. Next lines of code are not reproduced here. I would suppose other engines do the same. Otherwise the behavior is undefined. A good read on this topic is John Resig's post here.

提交回复
热议问题