Home > Software engineering >  Create a class that is callable and with a callable constructor
Create a class that is callable and with a callable constructor

Time:12-05

Such as with the Boolean object. How can a class be made to have a static method that can be called just by calling the class itself, but also have a normal callable constructor?

CodePudding user response:

To create a class in JavaScript that is callable and has a callable constructor, you can define a class with a 'call' method and a constructor. Here is an example:

class MyClass {
  // This is the call method, which will be called when
  // the class is used as a function
  call(a,b,c) {
      return a b c;
  }

  // This is the constructor, which will be called when
  // the class is used with the `new` keyword
  constructor(a) {
      return a;
  }
}

Note that the call method is not a static method, so it must be called on an instance of the class. To create an instance of the class, you can use the new keyword, like this:

const instance = new MyClass();

// Call the call method on the instance
instance.call(1, 2, 3);

In this example, an instance of the MyClass class is created, and then the call method is called on that instance, passing the arguments 1, 2, and 3 to the method.

CodePudding user response:

If you need just shortname to get you method in special place you can create scope and put method in variable.

Example:

// GLOBAL SCOPE

{
// create local scope
// create variable
const methodByClass = myObject.getData;

// use it method
methodByClass();
}

Hope it helpful for you

CodePudding user response:

function MyClass(x) {
  if (new.target) {
    this.x = x * 2
   } else {
    return x * 2;
   }
  }
  
console.log( MyClass(3) )
console.log( new MyClass(4) )

I found the answer from this question

CodePudding user response:

You can also create this type of construct as a function, setting properties on instances using this:

function MyBool(value) {
    this.value = !!value

    return !!value
}

console.log(MyBool(1))
console.log(new MyBool(1))

This is also the way classes were created in JS before the class keyword was included in the language.

  • Related