你认为每个程序员都应该知道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已经分配了一个新值之后!

其他回答

确保在遍历对象属性时使用hasOwnProperty方法:

for (p in anObject) {
    if (anObject.hasOwnProperty(p)) {
        //Do stuff with p here
    }
}

这样做是为了只访问object的直接属性,而不使用原型链下面的属性。

您可以根据异常的类型捕获异常。引自MDC:

try {
   myroutine(); // may throw three exceptions
} catch (e if e instanceof TypeError) {
   // statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
   // statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
   // statements to handle EvalError exceptions
} catch (e) {
   // statements to handle any unspecified exceptions
   logMyErrors(e); // pass exception object to error handler
}

注意:条件捕获子句是Netscape(因此也是Mozilla/Firefox)扩展,它不是ECMAScript规范的一部分,因此不能依赖于特定的浏览器。

当你想从数组中删除一个元素时,可以使用delete操作符,如下所示:

var numbers = [1,2,3,4,5];
delete numbers[3];
//numbers is now [1,2,3,undefined,5]

正如您所看到的,元素被删除了,但是数组中留下了一个洞,因为元素被替换为一个未定义的值。

因此,要解决这个问题,不要使用删除,而是使用splice array方法…是这样的:

var numbers = [1,2,3,4,5];
numbers.splice(3,1);
//numbers is now [1,2,3,5]

splice的第一个参数是数组[index]中的序数,第二个参数是要删除的元素数量。

jQuery和JavaScript:

变量名可以包含许多奇数字符。我使用$字符来标识包含jQuery对象的变量:

var $links = $("a");

$links.hide();

jQuery的对象链接模式非常好,但是应用这个模式可能会让人有点困惑。幸运的是JavaScript允许你断行,就像这样:

$("a")
.hide()
.fadeIn()
.fadeOut()
.hide();

一般的JavaScript:

我发现通过使用自执行函数来模拟作用域很有用:

function test()
{
    // scope of test()

    (function()
    {
        // scope inside the scope of test()
    }());

    // scope of test()
}

您可以将“任何具有整数属性和长度属性的*对象转换为适当的数组,从而赋予它所有数组方法,如push、pop、splice、map、filter、reduce等。

Array.prototype.slice.call({"0":"foo", "1":"bar", 2:"baz", "length":3 }) 

//返回["foo", "bar", "baz"]

这适用于jQuery对象,html集合和来自其他框架的数组对象(作为整个数组类型的一种可能的解决方案)。我说,如果它有一个长度属性,你可以把它变成一个数组,这没有关系。有很多非数组对象都有length属性,在arguments对象之外。