Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Static Methods

JavaScript Static Methods

A static method is a method modified with the static keyword, also called a class method. It belongs to the class, not to an object, and can be called as ClassName.methodName before an object is instantiated.

A static method cannot be called on an object, only on the class.

Example

class

Runoob

{

constructor

(

name

)

{

this

.

name

=

name

;

}

static

hello

(

)

{

return

"

Hello!!

"

;

}

}

let

noob

=

new

Runoob

(

"

Runoob Tutorial

"

)

;

//

The 'hello()' method can be called on the class

document

.

getElementById

(

"

demo

"

)

.

innerHTML

=

Runoob

.

hello

(

)

;

//

A static method cannot be called through an instantiated object

//

document.getElementById("demo").innerHTML = noob.hello();

//

The above code will raise an error

Try it »

Calling a static method on an instance object raises an error:

If you want to use a static method in the object noob, you can pass it as a parameter:

Example

class

Runoob

{

constructor

(

name

)

{

this

.

name

=

name

;

}

static

hello

(

x

)

{

return

"

Hello

"

x

.

name

;

}

}

let

noob

=

new

Runoob

(

"

Runoob Tutorial

"

)

;

document

.

getElementById

(

"

demo

"

)

.

innerHTML

=

Runoob

.

hello

(

noob

)

;

Try it »