假设x是一个对象......有什么好处:
if (typeof x.foo != "undefined")
Run Code Online (Sandbox Code Playgroud)
与做
if (x.foo)
Run Code Online (Sandbox Code Playgroud)
?
我在阅读这篇博文时提出了这个问题: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);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,this._listeners [type]将永远不会是除数组之外的任何东西 - 所以在这种情况下它只是做得更干净
addListener: function(type, listener){
if (!this._listeners[type]){
this._listeners[type] = [];
}
this._listeners[type].push(listener);
Run Code Online (Sandbox Code Playgroud)
?
另外,作为一个附带问题,我不知道他为什么这样做:
EventTarget.prototype = {
constructor: EventTarget
Run Code Online (Sandbox Code Playgroud)
调用new EventTarget()时,默认情况下构造函数是否已设置为EventTarget('this')?
Ray*_*nos 10
注意真正的价值观.
if (x.foo) 如果x.foo是,则不会运行
凡为if (typeof x.foo !== "undefined") {只检查值是否undefined
替代检查将是
if (x.foo !== undefined) { 和 if (x.foo !== void 0) {
要小心,undefined可以覆盖为局部变量
undefined = true是一个有效的声明,将破坏您的所有代码.当然,你永远不会在生产中看到这个代码,所以你真的不必屏蔽它,它只是需要警惕的东西.
我个人倾向于使用
if (x.foo != null) {
...
}
Run Code Online (Sandbox Code Playgroud)
检查两者null和undefined.
[[编辑]]
在您的具体实例它要么一个Array或undefined因此!foo是安全的.我个人更喜欢专门为检查undefined,让用户知道,我只希望它运行时,它的不确定,而当它是null或false或"".这使代码更加明确/自我记录.
至于
EventTarget.prototype = {
constructor: EventTarget
Run Code Online (Sandbox Code Playgroud)
如果EventTarget.prototype使用新对象覆盖,则EventTarget.prototype.constructor属性将丢失,需要再次设置.
.constructor如果只是通过调用扩展原型,则无需再次设置EventTarget.prototype.method = ....