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
原文链接:https://www.f2er.com/note/421715.html因为 Method 是Function 的实例,所以Function.prototype自定义添加的属性会显示。
而对Method.prototype而言,Method只是一个构造函数(类似合作关系),所以 talk()不会被找到。 (__proto__与prototype区别)