0

How must a function be 'chained', in order to call this function like this

F('Test').custom_substring(0,1);
5
  • 1
    it must return what you need to use after that function is run. Commented Aug 31, 2014 at 10:11
  • addition to @keune like you can sat "Test".replace("T","").replace("e","").... because replace returns a string which you can call letter. Commented Aug 31, 2014 at 10:13
  • @Mritunjay But how can I make a function, that I can call like Value.function Commented Aug 31, 2014 at 10:18
  • See the answer bellow. Commented Aug 31, 2014 at 10:21
  • possible duplicate of How to chain functions without using prototype? Commented Aug 31, 2014 at 14:26

3 Answers 3

2

You have to return an object that has a method member named custom_substring. One example:

var F = function(){
  return {
    custom_substring:function(){
      console.log('custom substring');
      return this;
    }
  }
}

F('Test')
  .custom_substring(0,1)
  .custom_substring(0,1)
  .custom_substring(0,1);

To create objects you can use constructor functions and prototype, this is a complex subject and explained here.

I would not mess with the String.prototype because that breaks encapsulation.

Sign up to request clarification or add additional context in comments.

2 Comments

How can I return 'Test' back if I want only call F('Test'); ?
@user3744885 either add custom_substring to String.prototype but I would not advice it because that breaks encapsulation or implement a valueOf and toString method in the returned object.
1

The following sample provides a chainable custom_substring that does not modify the original object but instead returns a new one. This is similar to how jQuery and other libraries work (and how built-in string operations work) and it helps make for safer and more predictable code.

function F(str) {
    return {
        toString: function () { return str; },

        // You didn't provide an example of what you want custom_substring
        // to do, so I'll have it append a "!" to the beginning of the resulting value
        // (since I can't think of anything else for it to do)
        custom_substring: function (from, to) {
            return F("!" + str.substring(from, to));
        }
    };
}

var s1 = F("Hello everyone");
var s2 = s1.custom_substring(0, 7);
var s3 = s2.custom_substring(0, 5)
           .custom_substring(0, 4);

console.log(s1);  // Hello everyone
console.log(s2);  // !Hello e
console.log(s3);  // !!!He

4 Comments

Is there a equivalent for toString: ..., if you have (like in libraries) a string as input and want to return an element as 'default'?
@user3744885 Could you give a more specific example? I'm not sure what you mean.
I want a function I call F('id_of_an_element'), that returns me the document.getElementById() of the parameter, but I still want to have other 'subfunctions' like F('test').custom_substring;
@user3744885 Ok, and what would custom_substring do in this case (if F('test') is selecting elements. And have you considered creating a jQuery plugin for this instead of reinventing the wheel?
-1

If you really want to create chainloading you need always return this from methods where it's possible.

For example we have some class with some methods:

function Foo() {
    this.foo = 'bar';
    return this;
}

Foo.prototype = Object.create({
    sayFoo: function() {
        console.log(this.foo);
        return this;
    },

    getFoo: function() {
        return this.foo; // Here you can't make chainload
    },

    saySmth: function() {
        console.log('Something');
        return this;
    }
});

And we can use this:

var test = new Foo().sayFoo().saySmth().getFoo(); // prints this.foo -> 'Something' -> returns this.foo
console.log(test); // prints out this.foo

3 Comments

WTH is Object.create good for? Btw, you don't need to return this from a constructor
@Bergi Are you seriously? Object.create creates object with prototype, read ECMA-262. For creating chainloading effect needs return this from a constructor. Oh man, you need read a lot of books.
I know very well what it does, I'm trying to tell you that it's useless (if not wrong) where you use it. And no, you don't need to return this from constructors. Oh man, you should throw away your books (I have tried reading a few, but I mostly found them sprinkled with mistakes).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.