JS设计模式:函数添加方法addMethod

前端之家收集整理的这篇文章主要介绍了JS设计模式:函数添加方法addMethod前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Function.prototype.addMethod = function(name,fn) {
    this[name] = fn;
    return this;
}
Function.prototype.addProtoMethod = function(name,fn) {
    this.prototype[name] = fn;
    return this;
}

var Method = function() {};
Method.addMethod('checkName',function() { return this;});

var testA = new Method();

Method.addProtoMethod('checkAge',function() {return this;});

var testB = new Method();

Method.addMethod('checkName',function() { return this.print();});

Function.prototype.print = function() {console.log('666');}

Method.checkName() //666

Method本身可以调用原型链上的addMethod(),他的实例不会有checkName(),checkName()属于公有方法,checkAge()属于公有方法

> Function.prototype.addMethod = function(name,fn) {
...     this[name] = fn;
...     return this;
... }
[Function]
> Function.prototype.addProtoMethod = function(name,fn) {
...     this.prototype[name] = fn;
...     return this;
... }
[Function]
>
> var Method = function() {};
undefined
> Method.addMethod('checkName',function() { return this.print();});
{ [Function] checkName: [Function] }
> Function.prototype.print = function() {console.log('666');}

for(var property in Method) {
... console.log(property);
... }
checkName
addMethod
addProtoMethod
print

Method.prototype.talk = function() {return false;}
[Function]
for(var property in Method) {
... console.log(property); //
... }
checkName
addMethod
addProtoMethod
print
Method.test = function() {talk();}
[Function]
Method.test()
ReferenceError: talk is not defined

因为 Method 是Function 的实例,所以Function.prototype自定义添加属性显示
而对Method.prototype而言,Method只是一个构造函数(类似合作关系),所以 talk()不会被找到。 (__proto__与prototype区别)

猜你在找的程序笔记相关文章