// checklet arr = [1,2,3];// it inherits from Array.prototype?alert( arr.__proto__===Array.prototype ); // true// then from Object.prototype?alert( arr.__proto__.__proto__===Object.prototype ); // true// and null on the top.alert( arr.__proto__.__proto__.__proto__ ); // null// 一些方法在原型函式重疊let arr = [1,2,3]alert(arr); // 1,2,3 <-- the result of Array.prototype.toStringfunctionf() {}alert(f.__proto__==Function.prototype); // truealert(f.__proto__.__proto__==Object.prototype); // true, inherit from objects
// 原型物件可以添加或更改屬性,但不是好主意,因為他是全域物件,會造成衝突String.prototype.show=function() {alert(this);};"BOOM!".show(); // BOOM!// 當我們在做 polyfills 時,允許這樣做,因為舊版引擎還沒支持新功能,要手動加上if (!String.prototype.repeat) { // if there's no such method// add it to the prototypeString.prototype.repeat=function(n) {// repeat the string n times// actually, the code should be a little bit more complex than that// (the full algorithm is in the specification)// but even an imperfect polyfill is often considered good enoughreturnnewArray(n +1).join(this); };}alert( "La".repeat(3) ); // LaLaLa