我找到了这个.它有什么作用?
function G(a, b) {
var c = function() { };
c.prototype = b.prototype;
a.T = b.prototype;
a.prototype = new c;
}
Run Code Online (Sandbox Code Playgroud)
它看起来与 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"}
Run Code Online (Sandbox Code Playgroud)
编辑:该T属性只是用于知道子构造函数的“超级”构造函数是什么,我在其他地方看到过这种模式,例如在Pro JavaScript Design Patterns(第 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;
}
}
Run Code Online (Sandbox Code Playgroud)
也可以看看: