我们知道给object.prototype添加方法,可以让该方法对所有对象都可用。其实这样的方法对函数,数组,字符串,数字,正则表达式和布尔值同样适用。
举个例子,我们可以通过给Function.prototype添加方法使得该方法对所有函数都可用:
1 Function.prototype.addMethod(name, func) { 2 this.prototype[name] = func; 3 return this; 4 }
下面是一个具体实现例子:
Function.prototype.addMethod = function (name, func){ this.prototype[name] = func; return this; }; function Person () { //这是一个构造方法,所以他的prototype是指向Function.prototype的 } Person.addMethod("say", function (){ //用上文定义的addMethod方法给Person原型添加一个say方法 console.log("我是say方法"); }); var a = new Person(); a.say(); //控制台输出:我是say方法
通过给Function.prototype增加一个addMethod方法,下次我们给对象增加方法的时候就不用再输入prototype这几个字符,代码变得简洁多了。