From here:爲什麼沒有「新」的Array()。slice工作?
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.");
現在,爲什麼Array()
甚至返回一些有意義的事情,沒有一個new
操作?多數「類」的定義我見過JS回報undefined
如果不叫new
:
function User(name) {
this.name = name;
this.jump = function() {
console.log(name + " is jumping!");
}
}
assert(typeof(User("no New")) == 'undefined');
它不是那麼「爲什麼.slice()工作?」作爲「爲什麼Array()似乎和'new Array()'做同樣的事情?」 - 其中的答案可以概括爲「因爲規格說明」。請參見[Array(1)'和'new Array(1)']之間的區別是什麼?](http://stackoverflow.com/questions/5827008/whats-the-difference-between-array1-and-new-array1 -in-的JavaScript)。 – nnnnnn 2012-03-10 09:34:33
@nnnnnn - Aye,投票結束爲dup,謝謝。 – ripper234 2012-03-10 09:54:41