1

As far as I know there are 2 ways to create classes in javascript, with functions or class statements. If in the statement class, you can create static methods using static keywords. Then if it functions, how do you create static methods?

class SomeClass {
  myMethod() {
    console.log("Some");
  }
}

// equivalent to

function SomeClass() {
  this.myMethod = function() {
    console.log("Some");
  }
}

==================================================
==================================================
//Now static method

class SomeClass {
  static myMethod() {
    console.log("Some");
  }
}

// equivalent to

function SomeClass() {
  ???
}
1
  • 2
    Does this answer your question? Class vs. static method in JavaScript — Object.assign(SomeClass, { myStaticMethod1(...args){}, myStaticMethod2(...args){} }). Commented Jun 27, 2020 at 5:05

1 Answer 1

3

Static methods are simply methods put on the function itself. So, it's rather:

class SomeClass {
  static myMethod() {
    console.log("Some");
  }
}

// equivalent to

function SomeClass() {}

SomeClass.myMethod = function(){
  console.log("Some")
}

Also note (although this is off topic to your question), that your first two codes aren't equal.

They behave identically up to a point, but they're different.

classes define methods on their prototype, while your function stuff creates it on a per-instance basis. Thus:

class SomeClass {
  myMethod() {
    console.log("Some");
  }
}

function SomeFn() {
  this.myMethod = function() {
    console.log("Some");
  }
}

const a = new SomeClass
const b = new SomeFn
const a2 = new SomeClass
const b2 = new SomeFn

a.myMethod() //Some
b.myMethod() //Some

console.log(a.myMethod === a2.myMethod) //true
console.log(b.myMethod === b2.myMethod) //false

Therefore, it rather should be:

class SomeClass {
  myMethod() {
    console.log("Some");
  }
}

// equivalent to

function SomeClass() {}

SomeClass.prototype.myMethod = function() {
    console.log("Some");
}
Sign up to request clarification or add additional context in comments.

2 Comments

… which is already covered by the answers in the proposed duplicate target.
@user4642212 That's true, but I started writing before you found it. I did a quick search, but found nothing...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.