javascript - 间接使用时 Function.prototype 定义中的 'return this' 有什么用处?

标签 javascript

有四种情况-

案例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/

相关文章:

javascript - 转义 HTML 值是什么意思?

javascript - 如何在图表线上方添加渐变颜色?

javascript - 显示页面其他位置的 JavaScript 隐藏元素

JavaScript:如何修改 <option> 中的值

javascript - MobX 和深度可观察性

javascript - instagram api jquery 无法正确显示图片

javascript - 如何创建重定向到 URL 的 HTML 取消按钮

javascript - 当点击单元格,输入值,但该值与之前的值相同时,Google脚本触发事件

javascript - 脚本在浏览器中工作,但在 NodeJS 中不工作

javascript - 按一个值对嵌套数组排序,然后按另一个值排序