return this'在函数.间接使用时的原型定义

What is the utility of the 'return this' in Function.prototype definition when used indirectly?

本文关键字:定义 原型 this 函数 return      更新时间:2023-09-26

有四种情况

案例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中的方法,return thisFunction.prototype.method中的存在有什么不同呢?原型使用method()

下面是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语句。它的结尾是:Uncaught TypeError: Cannot read property 'method' of undefined