Translate

2011年4月17日日曜日

prototypeのメモ

/* Stringにアラートするメソッドを追加 */
String.prototype.say = function(){alert(this)};

var str = new String("すとりんぐ");
str.say(); //すとりんぐ


/* Numberの値を2倍にしてアラートするメソッドを追加 */
Number.prototype.doubleSay = function(){ alert(this * 2) };

var num = new Number(123);
num.doubleSay(); //246


/* Functionに名前をアラートするメソッドを追加 */
Function.prototype.nameSay = function(){ alert(this.name) };

function bar(){};
function foo(){};
bar.nameSay(); //bar
foo.nameSay(); //foo


/* Arrayに要素を全てアラートするメソッドを追加 */
Array.prototype.elementSay = function(){
    for(var i = this.length; i--;){
        alert(this[i]);
    }
};

var list = ["a", "b", "c", "d"];
list.elementSay(); //d → c → b → a

/* カスタムコンストラクタの場合 */
var Person = function(name){
    this.name = name;
}

Person.prototype.say = function(){
    alert("I am " + this.name);
};

var human = new Person("Tarou");
human.say(); //I am Tarou