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

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

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

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


当前回答

您可以动态地重新定义运行时环境的大部分内容,例如修改Array构造函数或定义undefined。并不是说你应该这样做,但它可以是一个强大的功能。

一种稍微不那么危险的形式是向现有对象添加helper方法。例如,你可以让IE6在数组上“原生”支持indexOf。

其他回答

你可以使用in操作符检查对象中是否存在键:

var x = 1;
var y = 3;
var list = {0:0, 1:0, 2:0};
x in list; //true
y in list; //false
1 in list; //true
y in {3:0, 4:0, 5:0}; //true

如果你觉得对象文字太丑,你可以将它与无参数函数提示结合起来:

function list()
 { var x = {};
   for(var i=0; i < arguments.length; ++i) x[arguments[i]] = 0;
   return x
 }

 5 in list(1,2,3,4,5) //true

下面是一些有趣的事情:

Comparing NaN with anything (even NaN) is always false, that includes ==, < and >. NaN Stands for Not a Number but if you ask for the type it actually returns a number. Array.sort can take a comparator function and is called by a quicksort-like driver (depends on implementation). Regular expression "constants" can maintain state, like the last thing they matched. Some versions of JavaScript allow you to access $0, $1, $2 members on a regex. null is unlike anything else. It is neither an object, a boolean, a number, a string, nor undefined. It's a bit like an "alternate" undefined. (Note: typeof null == "object") In the outermost context, this yields the otherwise unnameable [Global] object. Declaring a variable with var, instead of just relying on automatic declaration of the variable gives the runtime a real chance of optimizing access to that variable The with construct will destroy such optimzations Variable names can contain Unicode characters. JavaScript regular expressions are not actually regular. They are based on Perl's regexs, and it is possible to construct expressions with lookaheads that take a very, very long time to evaluate. Blocks can be labeled and used as the targets of break. Loops can be labeled and used as the target of continue. Arrays are not sparse. Setting the 1000th element of an otherwise empty array should fill it with undefined. (depends on implementation) if (new Boolean(false)) {...} will execute the {...} block Javascript's regular expression engine's are implementation specific: e.g. it is possible to write "non-portable" regular expressions.

[更新了一点,以回应良好的评论;请参阅评论]

在这个帖子中有几个答案告诉你如何去做 通过Array对象的原型扩展Array对象。这很糟糕 IDEA,因为它破坏了语句中的for (i)。

如果你不使用for (i in a) 代码中的任何地方?除非你自己的代码是 只有您正在运行的代码,这是不太可能的 在浏览器内部。我担心如果人们开始扩张 他们的数组对象像这样,堆栈溢出将启动 充斥着一堆神秘的JavaScript错误。

点击这里查看有用的细节。

具有公共接口的私有变量

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

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

您还可以使用前面提到的原型链spoon16扩展(继承)类和重写属性/方法。

在下面的例子中,我们创建了一个类Pet并定义了一些属性。我们还重写了继承自Object的. tostring()方法。

在此之后,我们创建了一个Dog类,它扩展了Pet并重写了. tostring()方法,再次改变了它的行为(多态性)。此外,我们还向子类添加了一些其他属性。

在此之后,我们检查继承链以显示Dog仍然是Dog类型、Pet类型和Object类型。

// Defines a Pet class constructor 
function Pet(name) 
{
    this.getName = function() { return name; };
    this.setName = function(newName) { name = newName; };
}

// Adds the Pet.toString() function for all Pet objects
Pet.prototype.toString = function() 
{
    return 'This pets name is: ' + this.getName();
};
// end of class Pet

// Define Dog class constructor (Dog : Pet) 
function Dog(name, breed) 
{
    // think Dog : base(name) 
    Pet.call(this, name);
    this.getBreed = function() { return breed; };
}

// this makes Dog.prototype inherit from Pet.prototype
Dog.prototype = new Pet();

// Currently Pet.prototype.constructor
// points to Pet. We want our Dog instances'
// constructor to point to Dog.
Dog.prototype.constructor = Dog;

// Now we override Pet.prototype.toString
Dog.prototype.toString = function() 
{
    return 'This dogs name is: ' + this.getName() + 
        ', and its breed is: ' + this.getBreed();
};
// end of class Dog

var parrotty = new Pet('Parrotty the Parrot');
var dog = new Dog('Buddy', 'Great Dane');
// test the new toString()
alert(parrotty);
alert(dog);

// Testing instanceof (similar to the `is` operator)
alert('Is dog instance of Dog? ' + (dog instanceof Dog)); //true
alert('Is dog instance of Pet? ' + (dog instanceof Pet)); //true
alert('Is dog instance of Object? ' + (dog instanceof Object)); //true

这个问题的两个答案都是从Ray Djajadinata的一篇很棒的MSDN文章中修改的代码。