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');
The specification explicitly dictates this:
When
Arrayis called as a function rather than as a constructor, it creates and initialises a newArrayobject. Thus the function callArray(…)is equivalent to the object creation expressionnew 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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With