// 原型物件可以添加或更改屬性,但不是好主意,因為他是全域物件,會造成衝突
String.prototype.show = function() {
alert(this);
};
"BOOM!".show(); // BOOM!
// 當我們在做 polyfills 時,允許這樣做,因為舊版引擎還沒支持新功能,要手動加上
if (!String.prototype.repeat) { // if there's no such method
// add it to the prototype
String.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 enough
return new Array(n + 1).join(this);
};
}
alert( "La".repeat(3) ); // LaLaLa