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

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

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

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


当前回答

闭包:

function f() { 
    var a; 
    function closureGet(){ return a; }
    function closureSet(val){ a=val;}
    return [closureGet,closureSet];
}

[closureGet,closureSet]=f(); 
closureSet(5);
alert(closureGet()); // gives 5

closureSet(15);
alert(closureGet()); // gives 15

这里的闭包并不是所谓的解构赋值([c,d] =[1,3]等价于c=1;d=3;)但事实上,在closureGet和closurereset中出现的a仍然指向同一个变量。即使在closureSet已经分配了一个新值之后!

其他回答

==运算符有一个非常特殊的属性,它创建了这个令人不安的等式(是的,我知道在其他动态语言中,如Perl,这种行为是预期的,但JavaScript通常不会尝试在比较中聪明):

>>> 1 == true
true
>>> 0 == false
true
>>> 2 == true
false

原型继承(由Douglas Crockford推广)彻底改变了在Javascript中思考负载的方式。

Object.beget = (function(Function){
    return function(Object){
        Function.prototype = Object;
        return new Function;
    }
})(function(){});

这是一个杀手!可惜几乎没有人使用它。

它允许你“生成”任何对象的新实例,扩展它们,同时保持一个(活的)原型继承链接到它们的其他属性。例子:

var A = {
  foo : 'greetings'
};  
var B = Object.beget(A);

alert(B.foo);     // 'greetings'

// changes and additionns to A are reflected in B
A.foo = 'hello';
alert(B.foo);     // 'hello'

A.bar = 'world';
alert(B.bar);     // 'world'


// ...but not the other way around
B.foo = 'wazzap';
alert(A.foo);     // 'hello'

B.bar = 'universe';
alert(A.bar);     // 'world'

简单的自包含函数返回值缓存:

function isRunningLocally(){
    var runningLocally = ....; // Might be an expensive check, check whatever needs to be checked.

    return (isRunningLocally = function(){
        return runningLocally;
    })();
},

昂贵的部分只在第一次调用时执行,之后所有函数所做的就是返回这个值。当然,这只对总是返回相同内容的函数有用。

window.name的值在页面更改时保持不变,如果在同一个域中(如果在iframe中,使用document),可以被父窗口读取。getElementById(“你的帧的ID”). contentwindow .name来访问它),并且只受可用内存的限制。

真实和虚假价值的概念。你不需要做这种事

if(someVar === undefined || someVar === zero) ...

只是做的事:

if (! someVar)。

每个值都有一个对应的布尔表示。