扩展原型而不是声明整个对象的优点

时间:2013-02-15 18:54:23

标签: javascript object prototype declaration

我应该何时使用第一种表示法:

var object = {
    a: function() {
        // object.a method body
    },
    b: function() {
        // object.b method body
    },
    c: function() {
        // object.c method body
    },
};

当第二个?

function Class() {};

Class.prototype.a = function() {
    // object.a method body
};

Class.prototype.b = function() {
    // object.b method body
};

Class.prototype.c = function() {
    // object.c method body
};

var object = new Class();

1 个答案:

答案 0 :(得分:2)

主要优点是在第二种情况下所有实例共享这些函数,这使得对象更轻。它明确地将对象定义为概念上类的实例。

但正确的语法是

function MyClass(){
}
MyClass.prototype.a = function(){
};
...
var o = new MyClass();

它还允许您定义继承链:

function OtherClass(){
}
OtherClass.prototype = new MyClass(); // makes OtherClass extend MyClass
OtherClass.prototype.b = function(){
};
...
var o2 = new OtherClass();

o2具有OtherClassMyClass的功能。

MDN在其Introduction to Object-Oriented JavaScript中提供了更多详细信息。