/    Sign up×
Community /Pin to ProfileBookmark

Help with understanding chaining in Javascript

hi All,
I have question around Douglas Crockford “method” method.

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

azerizor.method(‘toString’, function () {

return this.value;
});
var me = new azerizor(‘salam’).toString();

alert(me);[/code]

this is it. But here arises question regarding return this?
what does mean here return this? this method works without return this. I have read about that. so that one say that it is for chaining. But i didnt understand how can i use chaining using this “method” function. Thanks in advance for attention. I will wait your responses!

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@bionoidJan 27.2013 — The chaining mechanism is handy if you want to add more than just one prototype to the function you're extending, for example:

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


azerizor
.method('toString', function() {return this.value;})
[COLOR="#FF0000"].method('toStringMore', function() {return this.value + ' more';})[/COLOR]
[COLOR="#FF0000"].method('bothFuncs', function() {return this.toString() + ' ' + this.toStringMore();});[/COLOR]

var me = new azerizor('salam');

alert(me.toString());
alert(me.[COLOR="#FF0000"]toStringMore[/COLOR]());
alert(me.[COLOR="#FF0000"]bothFuncs[/COLOR]());


If "return this" was not included then the second and third calls to the "method" function would not have worked.

Just note that there is no semi-colon until right at the end of the chain.
Copy linkTweet thisAlerts:
@azegurbauthorJan 28.2013 — Thank you very much!
×

Success!

Help @azegurb spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...