Reputation: 30
How can I make a dot notation on a function, I mean like in jQuery's function. Example:
func("test_string").func2("test_string2");
Upvotes: 0
Views: 55
Reputation: 69
to make benefits of method chaining, you should have a base object that has multiple methods, and you should return the actual reference of the object in every method, so let's say you have a User object that looks like :
class User {
constructor(...args){
// object construction goes here
}
func(...args){
// Methods logic goes here
// Here we should return the actual object (instance of User class)
// which is referred by this
return this;
}
func2(...args){
// We do the same here
return this;
}
}
// We create an instance of User
const user = new User();
// Now we can chain our methods since each method return our object
user.func(args).func2(args);
Upvotes: 0
Reputation: 10591
You're effectively invoke method on func
's return value, so just make the return value (an object that) contains a member function func2
.
function func(str){
return { //return an object with func2
func2(str2){console.log(`${str} ${str2}`);}
}
}
func("test_string").func2("test_string2");
Upvotes: 1
Reputation: 136104
You simply return an object from the first funtion which itself has a function
function func(input){
console.log("You called func with: " + input);
return {
func2: function(x){
console.log("You called func2 with: " + x);
}
}
}
func("test_string").func2("test_string2");
Upvotes: 0
Reputation: 13623
jQuery either returns jQuery or it returns an object with methods. So if you wanted some function that would console log and return itself you could do something like this:
const myObj = {
logit: (str) => {
console.log(str);
return myObj;
}
}
myObj.logit('hello').logit('world');
Upvotes: 0