你认为每个程序员都应该知道JavaScript的哪些“隐藏特性”?
在看到以下问题的优质答案后,我认为是时候向JavaScript请求它了。
HTML的隐藏特性 CSS的隐藏特性 PHP的隐藏特性 ASP的隐藏特性。网 c#的隐藏特性 Java的隐藏特性 Python的隐藏特性
尽管JavaScript可以说是目前最重要的客户端语言(问问谷歌就知道了),但令人惊讶的是,大多数web开发人员很少意识到它的强大。
你认为每个程序员都应该知道JavaScript的哪些“隐藏特性”?
在看到以下问题的优质答案后,我认为是时候向JavaScript请求它了。
HTML的隐藏特性 CSS的隐藏特性 PHP的隐藏特性 ASP的隐藏特性。网 c#的隐藏特性 Java的隐藏特性 Python的隐藏特性
尽管JavaScript可以说是目前最重要的客户端语言(问问谷歌就知道了),但令人惊讶的是,大多数web开发人员很少意识到它的强大。
当前回答
生成器和迭代器(仅适用于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");
}
其他回答
这里有一些捷径:
var a = []; // equivalent to new Array()
var o = {}; // equivalent to new Object()
您可以动态地重新定义运行时环境的大部分内容,例如修改Array构造函数或定义undefined。并不是说你应该这样做,但它可以是一个强大的功能。
一种稍微不那么危险的形式是向现有对象添加helper方法。例如,你可以让IE6在数组上“原生”支持indexOf。
具有公共接口的私有变量
它使用了一个简洁的小技巧,即自调用函数定义。 返回的对象中的所有内容在公共接口中都是可用的,而其他所有内容都是私有的。
var test = function () {
//private members
var x = 1;
var y = function () {
return x * 2;
};
//public interface
return {
setx : function (newx) {
x = newx;
},
gety : function () {
return y();
}
}
}();
assert(undefined == test.x);
assert(undefined == test.y);
assert(2 == test.gety());
test.setx(5);
assert(10 == test.gety());
未定义就是未定义。所以你可以这样做:
if (obj.field === undefined) /* ... */
名称空间
在较大的JavaScript应用程序或框架中,在名称空间中组织代码可能很有用。JavaScript没有内置模块或名称空间概念,但使用JavaScript对象很容易模拟。这将创建一个名为n的命名空间,并将函数foo附加到它上面。
if (!window.ns) {
window.ns = {};
}
window.ns.foo = function() {};
通常在整个项目中使用相同的全局名称空间前缀,并为每个JavaScript文件使用子名称空间。子名称空间的名称通常与文件名匹配。
一个叫做ns/button的文件头。应该是这样的:
if (!window.ns) {
window.ns = {};
}
if (!window.ns.button) {
window.ns.button = {};
}
// attach methods to the ns.button namespace
window.ns.button.create = function() {};