假设 x 是一个对象...这样做有什么好处吗:
if (typeof x.foo != "undefined")
对比做
if (x.foo)
?
我在阅读这篇博文时提出了这个问题: http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/
在他的例子中,他做了:
function EventTarget(){
this._listeners = {};
}
EventTarget.prototype = {
constructor: EventTarget,
addListener: function(type, listener){
if (typeof this._listeners[type] == "undefined"){
this._listeners[type] = [];
}
this._listeners[type].push(listener);
在这种情况下 this._listeners[type] 永远不会是数组以外的任何东西——所以在这种情况下这样做会更干净是不是真的
addListener: function(type, listener){
if (!this._listeners[type]){
this._listeners[type] = [];
}
this._listeners[type].push(listener);
?
另外,作为附带问题,我不明白他为什么这样做:
EventTarget.prototype = {
constructor: EventTarget
当您调用 new EventTarget() 时,默认情况下构造函数不是已经设置为 EventTarget ('this') 吗?
最佳答案
注意 truthy values .
if (x.foo)
如果 x.foo 是则不会运行
- 错误
- 无
- 未定义
- ""
- 0
- NaN
if (typeof x.foo !== "undefined") {
只检查值是否为 undefined
替代检查是
if (x.foo !== undefined) {
和 if (x.foo !== void 0) {
请注意 undefined
可以作为局部变量被覆盖
undefined = true
是一个有效的声明并且会破坏你所有的代码。当然,你永远不会在生产中看到这段代码,所以你真的不必屏蔽它,它只是需要警惕的东西。
我个人倾向于使用
if (x.foo != null) {
...
}
很多检查 null
和 undefined
。
[[编辑]]
在您的特定示例中,它是 Array
或 undefined
所以 !foo
是安全的。就我个人而言,我更喜欢专门检查 undefined
以便用户知道我只希望它在未定义时运行,而不是在 null
或 false
或“”
。这使代码更加明确/ self 记录。
至于
EventTarget.prototype = {
constructor: EventTarget
如果用新对象覆盖 EventTarget.prototype
,则 EventTarget.prototype.constructor
属性会丢失,需要重新设置。
如果您只是通过调用 EventTarget.prototype.method = ...
扩展原型(prototype),则不需要再次设置 .constructor
。
关于javascript - 显式 typeof == "undefined"检查与仅检查其存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5941629/