「哦,不,」我聽到你呻吟道,「不再是這個問題」,但忍耐一分鐘。Javascript原型 - 在這種情況下有什麼優勢?
我正試圖抓住原型,並且我理解跨對象實例共享通用功能的好處。但是,在下面的情況下,我通過使用原型而不是僅僅是一個獨立的函數獲得了什麼?
我想冒了一句和隨機化每個字的位置,這樣我可以做到以下幾點:
Array.prototype.shuffle = function() {
var i = this.length;
if (i == 0) return this;
while (--i) {
var j = Math.floor(Math.random() * (i + 1));
var a = this[i];
var b = this[j];
this[i] = b;
this[j] = a;
}
return this;
};
function randomiser(){
var s = "My name is Bob";
var shuffledSentence = s.split(' ').shuffle().join(' ');
console.log(shuffledSentence); // "Bob My name is"
}
或者,我可以用一個簡單的函數調用而不是隨機化我的字符串:
function randomise(arrayToRandomise){
var i = arrayToRandomise.length;
if (i == 0) return arrayToRandomise;
while (--i) {
var j = Math.floor(Math.random() * (i + 1));
var a = arrayToRandomise[i];
var b = arrayToRandomise[j];
arrayToRandomise[i] = b;
arrayToRandomise[j] = a;
}
return arrayToRandomise;
}
function randomiser(){
var s = "My name is Bob";
var shuffledSentence = s.split(' ');//.shuffle().join(' ');
var myShuffledString = this.randomise(shuffledSentence).join(' ');
console.log(myShuffledString); // "Bob My name is"
}
我在這裏通過使用原型獲得了什麼(除了更優雅的代碼!)?
就我個人而言,我遠離改變本地對象的原型,因爲它可以打破'for .. in',顯然它打破封裝:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/ Inheritance_and_the_prototype_chain#Bad_practice.3A_Extension_of_native_prototypes在您自己定義的對象中使用原型可以使用已知模式進行繼承,代碼重用等(OOP標準模式):http://stackoverflow.com/a/16063711/1641941 – HMR