JavaScript原型分配

时间:2014-05-08 17:26:36

标签: javascript

分配对象原型的推荐方法/模式是什么?为已经实例化的'super'function实例分配引用或初始化'super'的新实例每个'sub'function?如果,多种方法是司空见惯的;每个人的利弊是什么?

function SuperFoo(){ };
function Foo() {};
function Fooy() {};
function Fooimus() {};
function Foolacious() {};


/* Option 1: */ 
var proto = new SuperFoo();
Foo.prototype = proto;
Fooy.prototype = proto;
Fooimus.prototype = proto;
Foolacious.prototype = proto;


/* Option 2: */ 
Foo.prototype = new SuperFoo();
Fooy.prototype = new SuperFoo();
Fooimus.prototype = new SuperFoo();
Foolacious.prototype = new SuperFoo();

1 个答案:

答案 0 :(得分:4)

多种方法很常见。但一般来说,人们实际想要做的事实并未涵盖在您列出的任何解决方案中。

您通常希望从子类中获取的是一个构造函数,其prototype属性是一个对象,它本身继承自超类构造函数的prototype属性。它也是一个确保原型构造函数正确匹配的好主意:原型应该有一个constructor属性,指向它自己的类构造函数。结果可能如下所示:

function SuperFoo() {};  // assuming that some prototype functions are already defined.

function Foo() {};
Foo.prototype = Object.create(SuperFoo.prototype);
Foo.prototype.constructor = Foo;

我现在的常用解决方案是将这个rigamarole包装成一个函数,如下所示:

Object.subclass = function (sub, sup) {
    sub.prototype = Object.create(sup.prototype);
    sub.prototype.constructor = sub;
};

function SuperFoo() {};  // assuming that some prototype functions are already defined.

function Foo() {};
Object.subclass(Foo, SuperFoo);

function Fooy() {};
Object.subclass(Fooy, SuperFoo);

function Fooimus() {};
Object.subclass(Fooimus, SuperFoo);    

function Foolacious() {};
Object.subclass(Fooalicious, SuperFoo);