gpt4 book ai didi

javascript - 为什么除了 `goog.base(this)` 之外还需要 `goog.inherits()` ?

转载 作者:数据小太阳 更新时间:2023-10-29 05:52:57 25 4
gpt4 key购买 nike

在这段涉及构造函数的 Google Closure javascript 代码片段中,为什么 goog.base(this); 是必需的? Foo 不是已经通过 goog.inherits(foo, goog.Disposable); 从 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(){
...
}

最佳答案

goog.inherits(childConstructor, parentConstructor)

goog.inherits() 从子构造函数建立原型(prototype)链给父构造函数。

/**
* 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;
};


除了原型(prototype)属性,构造函数可能有“自己的”属性(即添加到 this 的特定于实例的属性)。自 goog.inherits()不调用父构造函数,自己的属性不复制到子构造函数和父级中的任何初始化代码都没有得到执行。由于这些原因,标准模式是 chain constructors如以下示例所示。

/**
* @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);


goog.base(self, opt_methodName, var_args)

goog.base() 是一个调用父方法的辅助函数,这样你就可以不需要显式使用 call()apply() .

If [goog.base()] is called from a constructor, then this calls the superclass contructor with arguments 1-N.

If this is called from a prototype method, then you must pass the name of the method as the second argument to this function. If you do not, you will get a runtime error. This calls the superclass' method with arguments 2-N.

This function only works if you use goog.inherits to express inheritance relationships between your classes.

在 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);


进一步阅读

关于javascript - 为什么除了 `goog.base(this)` 之外还需要 `goog.inherits()` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11122608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com