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;
}
- 它看起来很像
- 堆栈溢出:
对象。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;
}
}
另见:
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的目的是了解另一个构造函数是从哪个构造函数扩展的,请检查此模式。