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

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

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

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


当前回答

这是jQuery的一个隐藏特性,而不是Javascript,但因为永远不会有“jQuery的隐藏特性”的问题……

你可以在jQuery中定义自己的:something选择器:

$.extend($.expr[':'], {
  foo: function(node, index, args, stack) {
    // decide if selectors matches node, return true or false
  }
});

对于使用:foo的选择,例如$('div.block:foo("bar,baz") span'),函数foo将被用于匹配选择器中已经处理的部分的所有节点。论证的意义:

node holds the current node index is the index of the node in the node set args is an array that is useful if the selector has an argument or multiple names: args[0] is the whole selector text (e.g. :foo("bar, baz")) args[1] is the selector name (e.g. foo) args[2] is the quote character used to wrap the argument (e.g. " for :foo("bar, baz")) or an empty string if there is no quoting (:foo(bar, baz)) or undefined if there is no argument args[3] is the argument, including any quotes, (e.g. "bar, baz") or undefined if there are no arguments stack is the node set (an array holding all nodes which are matched at that point)

如果选择器匹配,函数将返回true,否则返回false。

例如,下面的代码将支持基于全文regexp搜索选择节点:

$.extend($.expr[':'], {
  matches: function(node, index, args, stack) {
    if (!args.re) { // args is a good place for caching
      var re = args[3];
      if (args[2]) { // get rid of quotes
        re = re.slice(1,-1);
      }
      var separator = re[0];
      var pos = re.lastIndexOf(separator);
      var modifiers = re.substr(pos+1);
      var code = re.substr(1, pos-1);
      args.re = new RegExp(code, modifiers);
    }
    return $(node).text().match(args.re);
  }
});

// find the answers on this page which contain /**/-style comments
$('.answer .post-text code:matches(!/\\*[\\s\\S]*\\*/!)');

使用.filter()的回调版本也可以达到类似的效果,但自定义选择器要灵活得多,通常可读性也更好。

其他回答

函数在JavaScript中是第一类公民:

var passFunAndApply = function (fn,x,y,z) { return fn(x,y,z); };

var sum = function(x,y,z) {
  return x+y+z;
};

alert( passFunAndApply(sum,3,4,5) ); // 12

函数式编程技术可以用来编写优雅的javascript。

特别是,函数可以作为参数传递,例如Array.filter()接受回调:

[1, 2, -1].filter(function(element, index, array) { return element > 0 });
// -> [1,2]

你也可以声明一个“private”函数,它只存在于特定函数的作用域中:

function PrintName() {
    var privateFunction = function() { return "Steve"; };
    return privateFunction();
}

生成器和迭代器(仅适用于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");
}

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

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

私有方法

对象可以有私有方法。

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

方法(或函数)可以在不是它们设计使用的类型的对象上调用。这对于在自定义对象上调用本机(快速)方法非常有用。

var listNodes = document.getElementsByTagName('a');
listNodes.sort(function(a, b){ ... });

这段代码崩溃是因为listNodes不是数组

Array.prototype.sort.apply(listNodes, [function(a, b){ ... }]);

这段代码之所以有效,是因为listNodes定义了足够多的类数组属性(length,[]运算符)供sort()使用。