Have been reading up on one of my favourite programmers Douglas Crockford, in particular the 'method' method.
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);
I am confused regarding the return this
.
What does return this
mean here?
The method works without it in what I have read is called chaining but how can I use chaining using this 'method' function and why is it useful?
thanks
From what I understand.
A changing mechanism is useful for when you want to add more than just one prototype to the function you are extending (object you are using).
See below for your example expanded:
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());
With the above if return this
was excluded then the result is that the 2nd and 3rd calls to the 'method' function would have failed.
Additionally see that there is no semi-colon until right at the end of the chain.
Hope that helps