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

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

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

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


当前回答

令人惊讶的是,很多人都没有意识到它也是面向对象的。

其他回答

还有一个几乎不为人知的JavaScript语法:

var a;
a=alert(5),7;
alert(a);    // alerts undefined
a=7,alert(5);
alert(a);    // alerts 7

a=(3,6);
alert(a);    // alerts 6

更多信息请点击这里。

私有方法

对象可以有私有方法。

function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;

    // A private method only visible from within this constructor
    function calcFullName() {
       return firstName + " " + lastName;    
    }

    // A public method available to everyone
    this.sayHello = function () {
        alert(calcFullName());
    }
}

//Usage:
var person1 = new Person("Bob", "Loblaw");
person1.sayHello();

// This fails since the method is not visible from this scope
alert(person1.calcFullName());

数字也是对象。所以你可以做一些很酷的事情,比如:

// convert to base 2
(5).toString(2) // returns "101"

// provide built in iteration
Number.prototype.times = function(funct){
  if(typeof funct === 'function') {
    for(var i = 0;i < Math.floor(this);i++) {
      funct(i);
    }
  }
  return this;
}


(5).times(function(i){
  string += i+" ";
});
// string now equals "0 1 2 3 4 "

var x = 1000;

x.times(function(i){
  document.body.innerHTML += '<p>paragraph #'+i+'</p>';
});
// adds 1000 parapraphs to the document

为变量分配默认值

你可以在赋值表达式中使用逻辑运算符||来提供一个默认值:

var a = b || c;

只有当b为false (if为null, false, undefined, 0,空字符串或NaN)时,变量a才会得到c的值,否则a将得到b的值。

这通常在函数中很有用,当你想在没有提供参数的情况下给参数一个默认值:

function example(arg1) {
  arg1 || (arg1 = 'default value');
}

事件处理程序中的IE回退示例:

function onClick(e) {
    e || (e = window.event);
}

以下语言特性已经伴随我们很长时间了,所有JavaScript实现都支持它们,但直到ECMAScript第5版才成为规范的一部分:

调试器语句

§12.15调试器语句描述

这个语句允许你通过以下方式在代码中添加断点:

// ...
debugger;
// ...

如果有调试器存在或处于活动状态,则会导致调试器立即在这一行上中断。

否则,如果调试器不存在或不活动,则此语句没有可观察到的效果。

多行字符串字面值

在§7.8.4字符串字面量中描述

var str = "This is a \
really, really \
long line!";

您必须小心,因为\旁边的字符必须是行结束符,例如,如果在\后面有空格,代码将看起来完全相同,但它将引发SyntaxError。

具有公共接口的私有变量

它使用了一个简洁的小技巧,即自调用函数定义。 返回的对象中的所有内容在公共接口中都是可用的,而其他所有内容都是私有的。

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());