gpt4 book ai didi

javascript - 为 Google Closure 类定义属性的首选方法是什么?

转载 作者:搜寻专家 更新时间:2023-11-01 04:26:39 24 4
gpt4 key购买 nike

下面的示例显示了一个扩展 goog.ui.Component 的类。

类的属性应该如下所示在构造函数之外定义,还是应该仅在构造函数中内联定义?

可以将属性初始化为 null 吗?

goog.provide("org.something.SomeClass");

/**
* @type {Object}
* @private
**/
org.something.SomeClass.prototype.anObject_ = null;

/**
* @type {Element}
* @private
**/
org.something.SomeClass.prototype.anElement_ = null;

/**
* @param {goog.dom.DomHelper=} opt_domHelper
* @constructor
* @extends {goog.ui.Component}
*/
org.something.SomeClass = function () {
goog.ui.Component.call(this, opt_domHelper);

this.anObject_ = {};
this.anElement_ = new Element();
};
goog.inherits(org.something.SomeClass, goog.ui.Component);

最佳答案

Closure Library实现具有在原型(prototype)和构造函数中定义的属性的类。除了研究 Closure Library 源代码之外,这里还有一些在决定是在原型(prototype)上还是在构造函数中定义属性时需要考虑的问题。

类的每个实例的属性是否唯一?

每个实例的唯一属性(例如汽车的 VIN 号)不应在实例之间共享,因此应在构造函数中定义,而不是在原型(prototype)中定义。

/**
* A car.
* @param {string} vin The Vehicle Identification Number.
* @constructor
*/
Car = function(vin) {

/**
* The Vehicle Identification Number.
* @type {string}
* @private
*/
this.vin_ = vin;
};

属性类型是不可变的(例如字符串、 bool 值、数字)还是可变的(例如对象、数组)?

由于不可变属性类型可以在实例之间安全地共享,因此应该在原型(prototype)上定义它们。如果实例需要覆盖共享的默认值,则可以添加一个实例属性来隐藏同名的原型(prototype)属性。

/**
* The number of cylinders in the engine.
* @type {number}
* @private
*/
Car.prototype.cylinders_ = 4;

/**
* Sets the number of cylinders in the engine.
* @param {number} cylinders The number of cylinders.
*/
Car.prototype.setCylinders = function(cylinders) {
if (this.cylinders_ == cylinders) {
// Since the number of cylinders has not changed, do not add a new
// instance property to shadow the prototype property. Instead, continue
// to use the prototype property.
return;
}

// Defines cylinders_ property on the instance object that shadows
// Car.prototype.cylinders_
this.cylinders_ = cylinders;
};

/**
* Gets the number of cylinders in the engine.
* @return {number} The number of cylinders.
*/
Car.prototype.getCylinders = function() {
return this.cylinders_;
};

以下示例说明设置实例属性如何隐藏原型(prototype)属性。

var myCar = new Car("1HGCM82633A004352");
alert(myCar.getCylinders()); // Alerts 4.

myCar.setCylinders(6);
alert(myCar.getCylinders()); // Alerts 6;

// Delete the instance property and let the prototype property
// "shine through".
delete myCar.cylinders_;
alert(myCar.getCylinders()); // Alerts 4;


如果属性类型是可变的,例如 Array 或 Object,那么在大多数情况下,您不希望在类的实例之间共享相同的可变属性实例。因此,可变属性更常在构造函数中定义,而不是在原型(prototype)中定义。

Is it ok to initialize properties to null?

Closure Library 中有许多示例将属性初始化为 null。 但是,最好尽可能将变量初始化为有用的默认值,例如将默认的柱面数设置为 4如上例所示。

关于javascript - 为 Google Closure 类定义属性的首选方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12211147/

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