JavaScript的隐藏功能? [关闭]

本文翻译自:Hidden Features of JavaScript? [closed]

What "Hidden Features" of JavaScript do you think every programmer should know? 您认为每个程序员应该知道哪些JavaScript的“隐藏功能”?

After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for JavaScript. 在看到以下问题的答案的优秀品质之后,我认为是时候向它询问JavaScript了。

Even though JavaScript is arguably the most important Client Side language right now (just ask Google) it's surprising how little most web developers appreciate how powerful it really is. 虽然JavaScript现在可以说是最重要的客户端语言(只是问谷歌)但令人惊讶的是,大多数网络开发人员都很少理解它的实力。


#1楼

参考:https://stackoom.com/question/FtI/JavaScript的隐藏功能-关闭


#2楼

Private variables with a Public Interface 具有公共接口的私有变量

It uses a neat little trick with a self-calling function definition. 它使用一个带有自调用函数定义的巧妙小技巧。 Everything inside the object which is returned is available in the public interface, while everything else is private. 返回的对象内的所有内容都可以在公共界面中使用,而其他所有内容都是私有的。

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

#3楼

Methods (or functions) can be called on object that are not of the type they were designed to work with. 可以在对象上调用方法(或函数),这些方法不是它们设计用于的类型。 This is great to call native (fast) methods on custom objects. 这很适合在自定义对象上调用本机(快速)方法。

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

This code crashes because listNodes is not an Array 此代码崩溃,因为listNodes不是Array

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

This code works because listNodes defines enough array-like properties (length, [] operator) to be used by sort() . 此代码有效,因为listNodes定义了sort()使用的sort()数组的属性(length,[] operator sort()


#4楼

Numbers are also objects. 数字也是对象。 So you can do cool stuff like: 所以你可以做很酷的事情:

// 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

#5楼

Some would call this a matter of taste, but: 有人会称之为品味,但是:

aWizz = wizz || "default";
// same as: if (wizz) { aWizz = wizz; } else { aWizz = "default"; }

The trinary operator can be chained to act like Scheme's (cond ...): 三元运算符可以被链接起来像Scheme(cond ...):

(cond (predicate  (action  ...))
      (predicate2 (action2 ...))
      (#t         default ))

can be written as... 可写成......

predicate  ? action( ... ) :
predicate2 ? action2( ... ) :
             default;

This is very "functional", as it branches your code without side effects. 这非常“实用”,因为它可以在没有副作用的情况下分支您的代码。 So instead of: 所以代替:

if (predicate) {
  foo = "one";
} else if (predicate2) {
  foo = "two";
} else {
  foo = "default";
}

You can write: 你可以写:

foo = predicate  ? "one" :
      predicate2 ? "two" :
                   "default";

Works nice with recursion, too :) 也适用于递归,:)


#6楼

Off the top of my head... 脱离我的头顶......

Functions 功能

arguments.callee refers to the function that hosts the "arguments" variable, so it can be used to recurse anonymous functions: arguments.callee是指托管“arguments”变量的函数,因此它可用于递归匿名函数:

var recurse = function() {
  if (condition) arguments.callee(); //calls recurse() again
}

That's useful if you want to do something like this: 如果你想做这样的事情,这很有用:

//do something to all array items within an array recursively
myArray.forEach(function(item) {
  if (item instanceof Array) item.forEach(arguments.callee)
  else {/*...*/}
})

Objects 对象

An interesting thing about object members: they can have any string as their names: 关于对象成员的一个有趣的事情:它们可以有任何字符串作为其名称:

//these are normal object members
var obj = {
  a : function() {},
  b : function() {}
}
//but we can do this too
var rules = {
  ".layout .widget" : function(element) {},
  "a[href]" : function(element) {}
}
/* 
this snippet searches the page for elements that
match the CSS selectors and applies the respective function to them:
*/
for (var item in rules) {
  var elements = document.querySelectorAll(rules[item]);
  for (var e, i = 0; e = elements[i++];) rules[item](e);
}

Strings 字符串

String.split can take regular expressions as parameters: String.split可以将正则表达式作为参数:

"hello world   with  spaces".split(/\s+/g);
//returns an array: ["hello", "world", "with", "spaces"]

String.replace can take a regular expression as a search parameter and a function as a replacement parameter: String.replace可以将正则表达式作为搜索参数,将函数作为替换参数:

var i = 1;
"foo bar baz ".replace(/\s+/g, function() {return i++});
//returns "foo1bar2baz3"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值