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?
Asked
Active
Viewed 104 times
-2
-
1When a function is called as a constructor, the value of `this` is a new object that has the function as its constructor. If a function doesn't see that being the case, it can behave differently than it would if called as a constructor. – Pointy Dec 05 '22 at 02:08
-
@Pointy That's not what I mean, they would be two separate methods – Aidan Dec 05 '22 at 02:13
-
It is not at all clear what you're talking about. There's only one `Boolean` function. It can be used as a constructor or as a function. There are not two of them, just one. – Pointy Dec 05 '22 at 02:20
-
@Pointy See my answer, essentially I was looking for the ability to write different behavior depending on if the reference was called a constructor or not, such as with `Boolean` – Aidan Dec 05 '22 at 02:32
-
I'm glad you found a solution, but please note that what you ended up doing is pretty much exactly what I said in the original comment. – Pointy Dec 05 '22 at 02:33
-
1FWIW, functions in JavaScript can be *callable* or *constructable* or both. "Normal" function definitions create a functions that are both. Functions/constructors created via `class` are only constructable and arrow functions (and methods I believe (not sure)) are only callable. – Felix Kling Dec 05 '22 at 10:29
3 Answers
0
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

gureenkov56
- 172
- 3
-
No, this isn't what I meant. Instead, I am wanting to have a single reference that is both callable, and has a constructor – Aidan Dec 05 '22 at 02:15
0
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

Aidan
- 413
- 3
- 22
-
Right, exactly, and there's only one function as I said originally in my comment. – Pointy Dec 05 '22 at 02:32
0
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.

Lionel Rowe
- 5,164
- 1
- 14
- 27