有四种情况-
案例1:
Function.prototype.method = function(name, func){
this.prototype[name] = func;
//return this;
};
Number.method("testMethod",function(){
//return Math[ this < 0 ? "ceil" : "floor" ](this);
});
console.log(typeof (9.3).testMethod()); //outputs undefined
案例2:
Function.prototype.method = function(name, func){
this.prototype[name] = func;
//return this;
};
Number.method("testMethod",function(){
return Math[ this < 0 ? "ceil" : "floor" ](this);
});
console.log(typeof (9.3).testMethod()); //outputs number
案例3:
Function.prototype.method = function(name, func){
this.prototype[name] = func;
return this;
};
Number.method("testMethod",function(){
//return Math[ this < 0 ? "ceil" : "floor" ](this);
});
console.log(typeof (9.3).testMethod()); //also outputs undefined
案例4:
Function.prototype.method = function(name, func){
this.prototype[name] = func;
return this;
};
Number.method("testMethod",function(){
return Math[ this < 0 ? "ceil" : "floor" ](this);
});
console.log(typeof (9.3).testMethod()); //outputs number
我知道“返回此”将有助于链接添加的 method()
。
在这些情况下,如果我要使用添加到 Function 的方法,Function.prototype.method
中存在 return this
会产生什么区别。使用 method()
进行原型(prototype)设计。
最佳答案
这是带有return
的代码:
Function.prototype.method = function(name,func){
this.prototype[name] = func;
return this;
}
function test(){
}
test.method('get',function(){
console.log('get method');
}).method('put',function(){
console.log('put method');
});
它工作得很好,但是如果你删除return
语句。最终结果是:
未捕获类型错误:无法读取未定义的属性“方法”
关于javascript - 间接使用时 Function.prototype 定义中的 'return this' 有什么用处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39653802/