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() {
  ???
}
  • 2
    Does this answer your question? [Class vs. static method in JavaScript](https://stackoverflow.com/questions/7694501/class-vs-static-method-in-javascript) — `Object.assign(SomeClass, { myStaticMethod1(...args){` … `}, myStaticMethod2(...args){` … `} })`. – Sebastian Simon Jun 27 '20 at 05:05

1 Answers1

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");
}
FZs
  • 16,581
  • 13
  • 41
  • 50