random13eves
random13eves

Reputation: 30

How can I make a dot nation on a function?

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

Answers (4)

AMEZIANE Adnane
AMEZIANE Adnane

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

apple apple
apple apple

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

Jamiec
Jamiec

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

Alexander Nied
Alexander Nied

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

Related Questions