Javascript 这有什么用?

Javascript 这有什么用?,javascript,Javascript,我找到了这个。它有什么作用 function G(a, b) { var c = function() { }; c.prototype = b.prototype; a.T = b.prototype; a.prototype = new c; } 它看起来很像 堆栈溢出: 它看起来类似于Crockford的对象。create方法,但此函数用于“设置”构造函数 它接受两个构造函数作为参数,并设置第一个构造函数的prototype 让我重命名这些神秘的变量名: functio

我找到了这个。它有什么作用

function G(a, b) {
  var c = function() { };
  c.prototype = b.prototype;
  a.T = b.prototype;
  a.prototype = new c;
}
  • 它看起来很像
  • 堆栈溢出:

它看起来类似于Crockford的
对象。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"}
Edit:使用
T
属性可以简单地知道sub-one的“super”构造函数是什么,我在其他地方也看到过这种模式,比如在Pro JavaScript Design Patterns()一书中,添加了一些内容,以防止
构造函数
属性指向错误的对象:

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;
    }
}
另见:


它似乎让您能够传入一个函数,对其进行更改,然后将其传回—a.prototype是它的新实例化副本。网上有一些例子使用这种类型的代码来“获取”和“设置”。

我猜你问的是“为什么有人会这样做?”,因为除了回答“迷惑人”,我没有任何东西可以给你。你在哪里找到的?设置的
T
属性不是我所见过的关于原型继承的任何模式的典型。但我认为这可能是继承了构造函数和原型链。我不认为这有那么简单,
t
属性是以某种方式使用的,这个问题并不清楚。此外,只需设置
Sub.prototype=Super.prototype
@Sean不太可能,就可以得到答案的结果。通过这样做,如果您向
Sub.prototype
添加一个成员,那么您也将向
Super.prototype
@CMS添加一个成员。我认为值得注意的是
member2
将位于
new Sub()
的原型链上,而不是
new Sub()
本身。@Pablo,不完全是,
member2
是自己的财产,例如,
new Sub().hasOwnProperty('member2');//true
@Sean,T的目的是了解另一个构造函数是从哪个构造函数扩展的,请检查此模式。