www.webdeveloper.com
Results 1 to 3 of 3

Thread: Help with understanding chaining in Javascript

  1. #1

    Help with understanding chaining in Javascript

    hi All,
    I have question around Douglas Crockford "method" method.

    PHP Code:
    Function.prototype.method = function (namefunc) {
        
    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); 
    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!

  2. #2
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    778
    The chaining mechanism is handy if you want to add more than just one prototype to the function you're extending, for example:

    Code:
    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;})
    	.method('toStringMore', function() {return this.value + ' more';})
    	.method('bothFuncs',    function() {return this.toString() + ' ' + this.toStringMore();});
    
    var me = new azerizor('salam');
    
    alert(me.toString());
    alert(me.toStringMore());
    alert(me.bothFuncs());
    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.
    JavaScript: Learn | Validate | Compact

  3. #3

    resolved

    Thank you very much!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles