2013-03-09 82 views
2
var MyClass = function() {};  

    MyClass.method = function (name, age) { 
     return "My name is " + name + " and I'm " + age + " years old";   
    } 

    MyClass.prototype.method = function (name, age) { 
     return "My name is " + name + " and I'm " + age + " years old"; 
    } 

    console.log(MyClass.method('David','30')); 

    var instance = new MyClass();  

    console.log(instance.method('john', '23')); 

在上面的代碼片段中,兩種方法都是做同樣的事情。在大多數情況下,兩者可以互換使用。你會選擇哪一個,爲什麼?對象方法vs原型方法

回答

3

原型方法在所有實例之間共享,這使得對象更輕。

+0

是否有任何理由使用非原型方法呢? – 2013-03-09 16:39:57

+0

如果你不想每個實例都有特定的方法,並且你使用'new'聲明瞭對象,那麼沒有理由。 – 2013-03-09 16:41:51

+0

儘可能使用構造函數/原型,效率更高。這是真的嗎? – 2013-03-11 15:52:22

0

它就像C#或Java中的靜態成員vs實例成員一樣。例如,非原型將無法訪問對象內的參數。

您將無法例如,因爲你調用它MyClass的,不是 MyClass的一個實例中MyClass.method做到這一點。 (jsFiddle)

var MyClass = function(name, age) { 
    this.name = name; 
    this.age = age; 
}; 

MyClass.prototype.method = function() { 
    return "My name is " + this.name + " and I'm " + this.age + " years old"; 
} 

var instance = new MyClass('David', 10); 
console.log(instance.method());