Javascript Design Patterns-Jsクラス

3208 ワード

JavaScript is a class-less laggage,however clases can be simulted using functions. 
eg:
// A car 'class'
function Car(model) { 
    this.model = model; 
    this.color = 'silver'; 
    this.year = '2012'; 
    this.getInfo = function () {
        return this.model + ' ' + this.year; 
    }
}
We can then instantiate the object using the Card construct we defined above like this: 
var myCar = new Car('ford'); 
myCar.year = '2010'; 
console.log(myCar.getInfo());
 
もう一つの例
var Person = function (name) { 
    this.name = name;
    this.say = function () {
        return "I am " + this.name; 
    };
};

// use the class
var adam = new Person("Adam"); 
adam.say(); // "I am Adam"
 
上述のクラス関数に関するやり方の性能がよくない理由は以下の通りである.
any time you call new Person()a new function is created in memory.
This is is oviously inefficient,because the say()method doesn't change from one instance to the next.
(newオブジェクトのたびにメモリに関数を新規作成します)
 
The better option is to add the method to the prototype of Person 
(良い方法はPersonオブジェクトのプロトタイプに方法を追加することです.)
Person.prototype.say = function () {
    return "I am " + this.name; 
};
 
just remember that reusable members、such as methods、shuld go to the prototype 
(JS類について覚えなければならないのは、再利用可能なメンバー、例えば方法は対象のプロトタイプに置かなければならない)