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

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

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

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


当前回答

Javascript在函数中有静态变量:

function someFunction(){
  var Static = arguments.callee;
  Static.someStaticVariable = (Static.someStaticVariable || 0) + 1;
  alert(Static.someStaticVariable);
}
someFunction() //Alerts 1
someFunction() //Alerts 2
someFunction() //Alerts 3

它在Objects内部也有静态变量:

function Obj(){
  this.Static = arguments.callee;
}
a = new Obj();
a.Static.name = "a";
b = new Obj();
alert(b.Static.name); //Alerts b

其他回答

访问:

http://images.google.com/images?q=disco

将以下JavaScript代码粘贴到浏览器的地址栏:

http://amix.dk/upload/awt/spin.txt http://amix.dk/upload/awt/disco.txt

享受JavaScript的迪斯科表演:-p

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

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

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

语法糖:内联for循环闭包

var i;

for (i = 0; i < 10; i++) (function ()
{
    // do something with i
}());

几乎打破了Douglas Crockford的所有代码惯例,但我认为它看起来很漂亮,从未减少:)


选择:

var i;

for (i = 0; i < 10; i++) (function (j)
{
    // do something with j
}(i));

与。

它很少被使用,坦率地说,很少有用……但是,在有限的情况下,它确实有它的用途。

例如:对象字面量对于快速在新对象上设置属性非常方便。但是,如果需要更改现有对象的一半属性,该怎么办呢?

var user = 
{
   fname: 'Rocket', 
   mname: 'Aloysus',
   lname: 'Squirrel', 
   city: 'Fresno', 
   state: 'California'
};

// ...

with (user)
{
   mname = 'J';
   city = 'Frostbite Falls';
   state = 'Minnesota';
}

Alan Storm指出,这可能有点危险:如果用作上下文的对象没有被赋值的属性之一,它将在外部作用域被解析,可能会创建或覆盖一个全局变量。如果你习惯了用默认值或空值未定义的对象编写代码,这是特别危险的:

var user = 
{
   fname: "John",
// mname definition skipped - no middle name
   lname: "Doe"
};

with (user)
{
   mname = "Q"; // creates / modifies global variable "mname"
}

因此,避免使用with语句进行这种赋值可能是一个好主意。

请参见:JavaScript的“with”语句是否有合法用途?

let.

与var缺乏块作用域对应的是let,在JavaScript 1.7中引入。

The let statement provides a way to associate values with variables within the scope of a block, without affecting the values of like-named variables outside the block. The let expression lets you establish variables scoped only to a single expression. The let definition defines variables whose scope is constrained to the block in which they're defined. This syntax is very much like the syntax used for var. You can also use let to establish variables that exist only within the context of a for loop.

  function varTest() {
        var x = 31;
    if (true) {
      var x = 71;  // same variable!
      alert(x);  // 71
    }
    alert(x);  // 71
  }

  function letTest() {
    let x = 31;
    if (true) {
      let x = 71;  // different variable
      alert(x);  // 71
    }
    alert(x);  // 31
  }

截至2008年,FireFox 2.0+和Safari 3.x支持JavaScript 1.7。