Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Array().slice without "new" work?

Tags:

javascript

From here:

function highest(){ 
  return makeArray(arguments).sort(function(a,b){ 
    return b - a; 
  }); 
} 

function makeArray(array){ 
  return Array().slice.call( array ); 
} 

assert(highest(1, 1, 2, 3)[0] == 3, "Get the highest value."); 
assert(highest(3, 1, 2, 3, 4, 5)[1] == 4, "Verify the results.");

Now, why does Array() even return something meaningful, without a new operator? Most "class" definitions I've seen in JS return undefined if called without new:

function User(name) {
  this.name = name;
  this.jump = function() {
    console.log(name + " is jumping!");
  }
}

assert(typeof(User("no New")) == 'undefined');
like image 513
ripper234 Avatar asked Nov 27 '25 10:11

ripper234


1 Answers

The specification explicitly dictates this:

When Array is called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.

How it's done internally depends on the implementation, but for custom constructors you can use the following trick:

if(!(this instanceof User)) return new User(name);

... because new User(...) sets this to the created User instance, whereas User(...) sets it to the global object. (So you were in fact setting global variables in the last snippet.)

like image 77
pimvdb Avatar answered Nov 29 '25 00:11

pimvdb