神奇的JavaScript之Function

标签: JavaScript Function

众所周知,在JavaScript中,内置对象有constructor属性指向它的构造函数,如:

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

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

1 Function.constructor === Function;//true

按上面等式得知:对象Function是构造函数Function的实例!

对象会继承它的构造函数的prototype属性所包含方法/属性,即对象可以访问到它的原型对象里方法/属性,那么

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

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

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

很多JavaScript库的源码里都会出现诸如下面代码,比如mootoolscore.js

 1 Function.prototype.overloadSetter = function(usePlural){
 2     var self = this;
 3     return function(a, b){
 4         if (a == null) return this;
 5         if (usePlural || typeof a != 'string'){
 6             for (var k in a) self.call(this, k, a[k]);
 7             if (enumerables) for (var i = enumerables.length; i--;){
 8                 k = enumerables[i];
 9                 if (a.hasOwnProperty(k)) self.call(this, k, a[k]);
10             }
11         } else {
12             self.call(this, a, b);
13         }
14         return this;
15     };
16 };
17 Function.prototype.implement = function(key, value){
18     this.prototype[key] = value;
19 }.overloadSetter();
20 //其实Function.implement === Function.prototype.implement
21 Function.implement({
22     hide: function(){
23         this.$hidden = true;
24         return this;
25     },
26     protect: function(){
27         this.$protected = true;
28         return this;
29     }
30 });

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

留言板
comments powered by Disqus