神奇的JavaScript之Function

 众所周知,在javascript中,每个内置对象都有一个constructor属性指向它的构造函数,比如:

1 ([]).constructor === Array;
2 ({}).constructor === Object;
3 (/./).constructor === RegExp;

这个很好理解,但是不知大家注意到没有,Function不仅是构造函数,而且还是对象,所以Function也有constructor属性,并且

1 Function.constructor === Function;

是不是不可思议。若按照上面等式可得出结论:对象Function是构造函数Function的实例!!
想必大家清楚,对象会继承它的构造函数的prototype属性所包含方法/属性,即对象可以访问到它的原型对象里方法/属性,那么

1 Function.call === Function.prototype.call;
2 Function.apply === Function.prototype.apply;

若向Function.prototype添加自定义方法/属性,那么Function也可访问得到的,

1 Function.prototype.sayHelloWorld = function(){
2     console.log('Hello World!');
3 };
4 Function.sayHelloWorld();//输出Hello World!

很多javascript库源码里都会出现诸如上面代码,比如mootools的core.js

Function.prototype.overloadSetter = function(usePlural){
    var self = this;
    return function(a, b){
        if (a == null) return this;
        if (usePlural || typeof a != 'string'){
            for (var k in a) self.call(this, k, a[k]);
            if (enumerables) for (var i = enumerables.length; i--;){
                k = enumerables[i];
                if (a.hasOwnProperty(k)) self.call(this, k, a[k]);
            }
        } else {
            self.call(this, a, b);
        }
        return this;
    };
};
Function.prototype.implement = function(key, value){
    this.prototype[key] = value;
}.overloadSetter();
//其实Function.implement === Function.prototype.implement
Function.implement({
    hide: function(){
        this.$hidden = true;
        return this;
    },
    protect: function(){
        this.$protected = true;
        return this;
    }
});

 若大家明白上述原理,就不会对上面代码感到莫名其妙。

原文地址:https://www.cnblogs.com/bender/p/3361191.html