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

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

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

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


当前回答

JavaScript使用了一个简单的对象文字:

var x = { intValue: 5, strValue: "foo" };

这将构造一个完整的对象。

JavaScript使用基于原型的面向对象,并提供了在运行时扩展类型的能力:

String.prototype.doubleLength = function() {
    return this.length * 2;
}

alert("foo".doubleLength());

对象将对不包含它自身的属性的所有访问委托给它的“原型”,另一个对象。这可以用来实现继承,但实际上更强大(即使更麻烦):

/* "Constructor" */
function foo() {
    this.intValue = 5;
}

/* Create the prototype that includes everything
 * common to all objects created be the foo function.
 */
foo.prototype = {
    method: function() {
        alert(this.intValue);
    }
}

var f = new foo();
f.method();

其他回答

当你想从数组中删除一个元素时,可以使用delete操作符,如下所示:

var numbers = [1,2,3,4,5];
delete numbers[3];
//numbers is now [1,2,3,undefined,5]

正如您所看到的,元素被删除了,但是数组中留下了一个洞,因为元素被替换为一个未定义的值。

因此,要解决这个问题,不要使用删除,而是使用splice array方法…是这样的:

var numbers = [1,2,3,4,5];
numbers.splice(3,1);
//numbers is now [1,2,3,5]

splice的第一个参数是数组[index]中的序数,第二个参数是要删除的元素数量。

JavaScript技巧或jslibs项目。

除了公共成员外,还可以使用闭包创建具有私有(在“类”定义之外不可访问)静态成员和非静态成员的“类”。

注意,下面的代码中有两种类型的公共成员。特定于实例的(在构造函数中定义),可以访问私有实例成员,共享成员(在原型对象中定义)只能访问私有静态成员。

var MyClass = (function () {
    // private static
    var nextId = 1;

    // constructor
    var cls = function () {
        // private
        var id = nextId++;
        var name = 'Unknown';

        // public (this instance only)
        this.get_id = function () { return id; };

        this.get_name = function () { return name; };
        this.set_name = function (value) {
            if (typeof value != 'string')
                throw 'Name must be a string';
            if (value.length < 2 || value.length > 20)
                throw 'Name must be 2-20 characters long.';
            name = value;
        };
    };

    // public static
    cls.get_nextId = function () {
        return nextId;
    };

    // public (shared across instances)
    cls.prototype = {
        announce: function () {
            alert('Hi there! My id is ' + this.get_id() + ' and my name is "' + this.get_name() + '"!\r\n' +
                  'The next fellow\'s id will be ' + MyClass.get_nextId() + '!');
        }
    };

    return cls;
})();

测试这段代码:

var mc1 = new MyClass();
mc1.set_name('Bob');

var mc2 = new MyClass();
mc2.set_name('Anne');

mc1.announce();
mc2.announce();

如果您有Firebug,您会发现除了在定义私有成员的闭包中设置断点之外,没有其他方法可以访问私有成员。

当定义需要严格验证值和完全控制状态更改的类时,这种模式非常有用。

要扩展这个类,你可以把MyClass.call(this);在扩展类的构造函数的顶部。您还需要复制MyClass。prototype对象(不要重用它,因为你也会改变MyClass的成员。

如果要替换announce方法,则需要调用MyClass。MyClass.prototype.announce.call(this);

原型继承(由Douglas Crockford推广)彻底改变了在Javascript中思考负载的方式。

Object.beget = (function(Function){
    return function(Object){
        Function.prototype = Object;
        return new Function;
    }
})(function(){});

这是一个杀手!可惜几乎没有人使用它。

它允许你“生成”任何对象的新实例,扩展它们,同时保持一个(活的)原型继承链接到它们的其他属性。例子:

var A = {
  foo : 'greetings'
};  
var B = Object.beget(A);

alert(B.foo);     // 'greetings'

// changes and additionns to A are reflected in B
A.foo = 'hello';
alert(B.foo);     // 'hello'

A.bar = 'world';
alert(B.bar);     // 'world'


// ...but not the other way around
B.foo = 'wazzap';
alert(A.foo);     // 'hello'

B.bar = 'universe';
alert(A.bar);     // 'world'

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。