0

I'm creating functions which are being chaining like jQuery with prototype like this:

String.prototype.rem = function (toRemove){
   return this.replace(toRemove,'');
}

var str = 'aaaasaaaa';
console.log(str.rem('s'))

That's only an example.

My question is that, is it true way to define chaining function. Or am I doing it wrong?

1
  • No, whether a method is "chaining" or not doesn't have anything to do with whether or what prototype it is defined on. Commented Oct 20, 2019 at 22:21

1 Answer 1

1

"Chaining" is related to "function call" and "return type".

"prototype" is related to common(or default) properties which live in constructor function.( factory of object instance )

not all "normal" method can change to chaining method. Method which return A value can not be chaining method. Method which have no return statement can be chaining method.

Check one of your method has async operation which may chain other sync method. Check error handling policy. It handled by you or user who use your library.

before design or implement chaining, Read about Type "Maybe" "Either" (Functional world!!!) It help you.

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

8 Comments

What do you mean by "Method which return A value"?
for method chaining. method must return object which is same instance or same type(implement same interface). If method return a different type of value as a result of function execution. it's not possible to chaining
I'd argue that it's still chaining when you next call methods of the other type, but regardless: that's not what the sentence in your answer says.
a().b().c(); // if a(), b(), c() returns different type. I think it's not chaining which @sundowatch says. according to his Question "chaining like Jquery"
I'd still consider $(…).find(…).val().toString().split() chaining just like jQuery.
|

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.