rel1x
rel1x

Reputation: 2441

What the different between `new Array(n)` and `Array(n)`

What the different if both of them call the constructor "Array" and generate an object?

I know that we lost this if we create some object without new:

function Animal(name) {this.name = name}
var duck = Animal('duck'); // undefined

But how that works for new Array(n) and Array(n)?

Upvotes: 1

Views: 108

Answers (3)

sapy
sapy

Reputation: 9592

JavaScript uses prototypal inheritance . When you use new command, It inherits from Object . Incase you want to inherit from an user defined object (e.g. Animal) you need to use new Animal() or without using new you can do it in following way.

   // Function object acts as a combination of a prototype 
     // to use for the new object and a constructor function to invoke:
     function Animal(name){
      this.name = name
     }

     var inheritFrom = function(parent, prop){
      // This is how you create object as a prototype of another object
      // var x = {} syntax can’t do this as it always set the newly
      //created object’s prototype to Object.prototype.

      var obj = Object.create(parent.prototype);
     // apply() method calls a function with a given this value 
     //and arguments provided as an array 

     parent.apply(obj, [prop]);
     return obj
    }
    var duck = inheritFrom(Animal, 'duck');
    console.log(duck.name);  // ‘duck’

Upvotes: 0

Yury Tarabanko
Yury Tarabanko

Reputation: 45106

Such behaviour for Array is described in spec. You can achive the same behaviour like this

function Animal(name) {
  if(!(this instanceof Animal)) {
     return new Animal(name);
  } 
  this.name = name
}

var duck = Animal('duck'); //Animal {name: "duck"}

But a better idea would be to follow a simple code style convention that all functions starting with a captial letter are constructors and should be called with new. And set up a linter you prefer to check your code follows this rule.

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

There is no difference. Check this article:

You never need to use new Object() in JavaScript. Use the object literal {} instead. Similarly, don’t use new Array(), use the array literal [] instead. Arrays in JavaScript work nothing like the arrays in Java, and use of the Java-like syntax will confuse you.

Do not use new Number, new String, or new Boolean. These forms produce unnecessary object wrappers. Just use simple literals instead.

...............................

So the rule is simple: The only time we should use the new operator is to invoke a pseudoclassical Constructor function. When calling a Constructor function, the use of new is mandatory.

Upvotes: 2

Related Questions