你认为每个程序员都应该知道JavaScript的哪些“隐藏特性”?

在看到以下问题的优质答案后,我认为是时候向JavaScript请求它了。

HTML的隐藏特性 CSS的隐藏特性 PHP的隐藏特性 ASP的隐藏特性。网 c#的隐藏特性 Java的隐藏特性 Python的隐藏特性

尽管JavaScript可以说是目前最重要的客户端语言(问问谷歌就知道了),但令人惊讶的是,大多数web开发人员很少意识到它的强大。


当前回答

如果你喜欢类似CLOS的基于类的OO, Joose是一个不错的对象系统。

// Create a class called Point
Class("Point", {
    has: {
        x: {
            is:   "rw",
            init: 0
        },
        y: {
            is:   "rw",
            init: 0
        }
    },
    methods: {
        clear: function () {
            this.setX(0);
            this.setY(0);
        }
    }
})

// Use the class
var point = new Point();
point.setX(10)
point.setY(20);
point.clear();

其他回答

生成器和迭代器(仅适用于Firefox 2+和Safari)。

function fib() {
  var i = 0, j = 1;
  while (true) {
    yield i;
    var t = i;
    i = j;
    j += t;
  }
}

var g = fib();
for (var i = 0; i < 10; i++) {
  document.write(g.next() + "<br>\n");
}

The function containing the yield keyword is a generator. When you call it, its formal parameters are bound to actual arguments, but its body isn't actually evaluated. Instead, a generator-iterator is returned. Each call to the generator-iterator's next() method performs another pass through the iterative algorithm. Each step's value is the value specified by the yield keyword. Think of yield as the generator-iterator version of return, indicating the boundary between each iteration of the algorithm. Each time you call next(), the generator code resumes from the statement following the yield. In normal usage, iterator objects are "invisible"; you won't need to operate on them explicitly, but will instead use JavaScript's for...in and for each...in statements to loop naturally over the keys and/or values of objects.

var objectWithIterator = getObjectSomehow();

for (var i in objectWithIterator)
{
  document.write(objectWithIterator[i] + "<br>\n");
}

你永远不需要使用eval()来组装全局变量名。

也就是说,如果你有几个名为spec_grapes, spec_apples的全局变量(无论出于什么原因),你不需要用eval("spec_" + var)访问它们。

所有全局变量都是window[]的成员,所以你可以执行window["spec_" + var]。

JavaScript没有块作用域(但它有闭包,所以让我们称它为偶数?)

var x = 1;
{
   var x = 2;
}
alert(x); // outputs 2

JavaScript使用Date()的方式让我很兴奋!

function isLeapYear(year) {
    return (new Date(year, 1, 29, 0, 0).getMonth() != 2);
}

这是真正的“隐藏特性”。

编辑:删除了评论中建议的“?”条件。 是:……new Date(year, 1,29,0,0).getMonth() != 2 ?真:假…… 详情请看评论。

如果您在google上搜索关于给定主题的像样的JavaScript参考,在查询中包含“mdc”关键字,那么您的第一个结果将来自Mozilla Developer Center。我没有随身携带任何离线参考资料或书籍。我总是使用“mdc”关键字来直接找到我要找的东西。例如:

谷歌:javascript数组排序mdc (在大多数情况下,你可以省略“javascript”)

更新:Mozilla开发者中心已重命名为Mozilla开发者网络。“mdc”关键字技巧仍然有效,但很快我们可能不得不开始使用“mdn”来代替。