Hidden Features of JavaScript? [closed]

2018-12-31 08:54发布

What "Hidden Features" of JavaScript do you think every programmer should know?

After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for 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.

30条回答
千与千寻千般痛.
2楼-- · 2018-12-31 09:32

I could quote most of Douglas Crockford's excellent book JavaScript: The Good Parts.

But I'll take just one for you, always use === and !== instead of == and !=

alert('' == '0'); //false
alert(0 == ''); // true
alert(0 =='0'); // true

== is not transitive. If you use === it would give false for all of these statements as expected.

查看更多
君临天下
3楼-- · 2018-12-31 09:33

Private Methods

An object can have private methods.

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());
查看更多
回忆,回不去的记忆
4楼-- · 2018-12-31 09:33

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 ...):

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

查看更多
看淡一切
5楼-- · 2018-12-31 09:34

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
查看更多
梦醉为红颜
6楼-- · 2018-12-31 09:34

Be sure to use the hasOwnProperty method when iterating through an object's properties:

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

This is done so that you will only access the direct properties of anObject, and not use the properties that are down the prototype chain.

查看更多
流年柔荑漫光年
7楼-- · 2018-12-31 09:35

You can access object properties with [] instead of .

This allows you look up a property matching a variable.

obj = {a:"test"};
var propname = "a";
var b = obj[propname];  // "test"

You can also use this to get/set object properties whose name is not a legal identifier.

obj["class"] = "test";  // class is a reserved word; obj.class would be illegal.
obj["two words"] = "test2"; // using dot operator not possible with the space.

Some people don't know this and end up using eval() like this, which is a really bad idea:

var propname = "a";
var a = eval("obj." + propname);

This is harder to read, harder to find errors in (can't use jslint), slower to execute, and can lead to XSS exploits.

查看更多
登录 后发表回答