A safety fence for your property lookups

javascript Add comments

Link:“Safety fence” for accessing properties

一个很有用的小技巧,在null.property的时候,将返回一个error而不是undefined。

所以为了避免这个问题,一般情况下我们这样写

if ((node) &&(node.nextSibling) &&(node.nextSibling.className == ...)

... ) {

...

}

在访问对象属性的时候,先要判断对象是否存在。

作者提出了以这样的方式

if ( next = (node || 0).nextSibling) ) {   ...}

这样原来上面那一串判断就变成了这样

if (((node || 0).nextSibling || 0).className == ...) {

   ...

}

是不是很Cool啊

  • Share/Bookmark

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Leave a Reply


WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in