2010-05-20 162 views
5

我找到了。它有什么作用?这是做什么用的?

function G(a, b) { 
    var c = function() { }; 
    c.prototype = b.prototype; 
    a.T = b.prototype; 
    a.prototype = new c; 
} 
+1

我猜你在问什么是“为什么有人会这样做?”,因为除了回答“迷惑人”之外,我没有任何东西可以帮你。 – wlangstroth 2010-05-20 14:56:04

+1

你从哪里找到这个?被设置的'T'属性并不是典型的关于原型继承的任何模式。 但我相信这可能是有继承的构造函数以及原型链。 – 2010-05-20 15:00:31

回答

1

它看起来类似于Crockford的Object.create方法,但该函数用于“设置”构造函数。

它接受两个构造函数作为参数,并且它设置了第一个构造函数的prototype

让我重新命名神秘的变量名:

function G(sub, super) { 
    var F = function() { }; 
    F.prototype = super.prototype; 
    sub.superLink = super.prototype; 
    sub.prototype = new F(); 
} 

function Super() { 
    //... 
} 
Super.prototype.member1 = 'superMember1'; 

function Sub() { 
    this.member2 = 'subMember2'; 
} 

G(Sub, Super); 

new Sub(); // Object { member2="subMember2", member1="superMember1"} 

编辑:T属性只是用来知道什么是子之一的“超级”的构造,我已经看到了这种模式的其他地方,如在书专业JavaScript的设计模式page 43),与一些补充,防止constructor属性指向了错误的对象:

function extend(subClass, superClass) { 
    var F = function() {}; 
    F.prototype = superClass.prototype; 
    subClass.prototype = new F(); 
    subClass.prototype.constructor = subClass; 

    subClass.superclass = superClass.prototype; 
    if(superClass.prototype.constructor == Object.prototype.constructor) { 
     superClass.prototype.constructor = superClass; 
    } 
} 

参见:

+1

我不认为它那么简单,'T'属性在某种程度上用于这个问题并不清楚。此外,只需设置'Sub.prototype = Super.prototype'就可以达到答案的结果 – 2010-05-20 14:59:14

+1

@Sean不完全。通过这样做,如果您将一个成员添加到'Sub.prototype',您还会将一个成员添加到'Super.prototype'。 – 2010-05-20 15:17:30

+0

@CMS我认为值得注意的是'member2'将在'new Sub()'的原型链上,而不是在'new Sub()'本身。 – 2010-05-20 15:18:01

0

它看起来像它可以让你在一个函数时,进行更改,然后传回的能力 - a.prototype是一个新的实例它的副本。网上有一些例子使用这种类型的代码来“获取”和“设置”。