dan*_*007 5 javascript inheritance prototypal-inheritance google-closure-library
在这个涉及构造函数的Google Closure javascript代码片段中,为什么有goog.base(this);必要?还没有Foo从Disposable继承goog.inherits(foo, goog.Disposable);吗?
goog.provide('Foo');
/**
* @constructor
* @extends {goog.Disposable}
*/
Foo = function() {
goog.base(this);
}
goog.inherits(foo, goog.Disposable);
foo.prototype.doSomething = function(){
...
}
foo.prototype.disposeInternal = function(){
...
}
Run Code Online (Sandbox Code Playgroud)
goog.inherits()建立从子构造函数到父构造函数的原型链.
/**
* Inherit the prototype methods from one constructor into another.
* @param {Function} childCtor Child class.
* @param {Function} parentCtor Parent class.
*/
goog.inherits = function(childCtor, parentCtor) {
/** @constructor */
function tempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
/** @override */
childCtor.prototype.constructor = childCtor;
};
Run Code Online (Sandbox Code Playgroud)
除了原型属性之外,构造函数可能具有"自己的"属性(即添加了特定于实例的属性this).由于goog.inherits()
不调用父构造函数,因此不会将自己的属性复制到子构造函数,并且不会执行父级中的任何初始化代码.由于这些原因,标准模式是链式构造函数,如下例所示.
/**
* @param {string} name The parent's name.
* @constructor
*/
var Parent = function(name) {
/**
* @type {string}
* @private
*/
this.name_ = name;
}
/**
* @param {string} name The child's name.
* @constructor
* @extends {Parent}
*/
var Child = function(name) {
Parent.call(this, name);
}
goog.inherits(Child, Parent);
Run Code Online (Sandbox Code Playgroud)
goog.base()是一个用于调用父方法的辅助函数,因此您不需要显式地使用call()或apply().
如果从构造函数调用[goog.base()],则会调用带有参数1-N的超类构造函数.
如果从原型方法调用此方法,则必须将方法的名称作为第二个参数传递给此函数.如果不这样做,您将收到运行时错误.这将使用参数2-N调用超类'方法.
此函数仅在您用于
goog.inherits表示类之间的继承关系时才有效.
在Closure代码中,通常链接构造函数goog.base()而不是显式调用父构造函数.
/**
* @param {string} name The child's name.
* @constructor
* @extends {Parent}
*/
var Child = function(name) {
goog.base(this, name);
}
goog.inherits(Child, Parent);
Run Code Online (Sandbox Code Playgroud)
goog.inherits()-经典模式#5 - 临时构造函数)