在Javascript中链接,为什么在这段代码中有用呢?

时间:2013-02-01 10:15:30

标签: javascript oop chaining

一直在阅读我最喜欢的程序员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);  

我对return this感到困惑 return this在这里的含义是什么? 该方法在没有它的情况下工作,我读到的称为链接但是如何使用这个'方法'函数来链接,为什么它有用呢?

感谢

1 个答案:

答案 0 :(得分:4)

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

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,那么结果就是对'方法'功能的第二次和第三次调用都会失败。
另外,看到直到链末端没有分号。

希望有所帮助