【问题标题】:Chaining in Javascript, why is it useful inside this code? [duplicate]在 Javascript 中链接,为什么它在这段代码中很有用? [复制]
【发布时间】:2013-02-01 10:15:29
【问题描述】:

一直在阅读我最喜欢的程序员之一 Douglas Crockford,尤其是“方法”方法。

JavaScript:

Function.prototype.method = function (name, func) { 
    this.prototype[name] = func; 
    return this; 
}; 
function myfunc(value) { 
this.value=value; 
} 

myfunc.method('toString', function () { 
    return this.value; 
}); 

var testvar = new myfunc('myself').toString(); 
alert(testvar);  

我对@9​​87654322@ 感到困惑。
return this 在这里是什么意思?
该方法在没有它的情况下也可以在我所阅读的内容中运行,但我如何使用这个“方法”函数来使用链接,为什么它有用?

谢谢

【问题讨论】:

    标签: javascript oop chaining


    【解决方案1】:

    据我了解。
    当您想向要扩展的函数(您正在使用的对象)添加多个原型时,更改机制非常有用。
    请参阅下面的扩展示例:

    Function.prototype.method = function(name, func)
    {
        this.prototype[name] = func;
        return this;
    };
    function myfunc(value)
    {
        this.value = value;
    }
    
    myfunc
        .method('toString',     function() {return this.value;})
        .method('toStringMore', function() {return this.value + ' more';})
        .method('bothFuncs',    function() {return this.toString() + ' ' + this.toStringMore();});
    
    var testvar = new myfunc('myself');
    
    alert(testvar.toString());
    alert(testvar.toStringMore());
    alert(testvar.bothFuncs());
    

    如果return this 被排除在外,那么结果是对“方法”函数的第二次和第三次调用将失败。
    另外请注意,直到链的末尾才没有分号。

    希望有帮助

    【讨论】:

    • 哦,对了,这就是它有用的原因以及如何在我的代码中实现。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多