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

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

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

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


当前回答

JavaScript typeof运算符用于数组或null总是返回对象值,在某些情况下可能不是程序员所期望的。

这里有一个函数,它将为这些项返回正确的值。数组识别复制自Douglas Crockford的书《JavaScript: The Good Parts》。

function typeOf (value) {
    var type = typeof value;
    if (type === 'object') {
        if (value === null) {
             type = 'null';
        } else if (typeof value.length === 'number' && 
            typeof value.splice === 'function' && 
            !value.propertyIsEnumerable('length')) {
            type = 'array';
        }
    }
    return type;
}

其他回答

模块模式

<script type="text/javascript">
(function() {

function init() {
  // ...
}

window.onload = init;
})();
</script>

没有使用var语句或在函数外部声明的变量和函数将在全局作用域中定义。如果一个同名的变量/函数已经存在,它将被无声地覆盖,这可能导致很难发现错误。一种常见的解决方案是将整个代码体封装到一个匿名函数中并立即执行它。这样,所有变量/函数都定义在匿名函数的作用域中,不会泄漏到全局作用域中。

要显式地在全局作用域定义一个变量/函数,它们必须以window为前缀:

window.GLOBAL_VAR = 12;
window.global_function = function() {};

函数在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();
}

具有公共接口的私有变量

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

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

私有方法

对象可以有私有方法。

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

我可以引用道格拉斯·克罗克福德这本好书的大部分内容 JavaScript:好的部分。

但我只给你一个,总是使用===和!==而不是==和!=

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

==是不可传递的。如果你使用===,它会给出false for 所有这些陈述都符合预期。