class myClass{
constructor(){
this.myLocaleVariable=1;//this.varname in the constructer function makes a locale var
}
localfunction(){
return "im local unique to this variable";
}
static publicfunction(){
return "i can be called without an obj"
}
}
myClass.myPublicVariable = 0;
myClass.localfunction();//error
myClass.publicfunction();//"i can be called without an obj"
myClass.myLocaleVariable;//error
myClass.myPublicVariable;//0
var obj = new myClass;
obj.localfunction();//"im local unique to this variable"
obj.publicfunction();//error
obj.myLocaleVariable;//1
obj.myPublicVariable;//error
class ClassWithInstanceField {
instanceField = 'instance field'
}
class ClassWithStaticField {
static staticField = 'static field'
}
class Thing {
static type = 'thing';
static myType() {
return `This class has a type of ${this.type}`;
}
}
console.log(Thing.type);
//=> 'thing'
console.log(Thing.myType());
//=> 'This class has a type of thing'
// Instances do not inherit static fields and methods
const t = new Thing();
console.log(t.type);
//=> undefined
console.log(t.myType())
//=> Uncaught TypeError: t.myType is not a function
class Hi {
constructor() {
console.log("hi");
}
my_method(){}
static my_static_method() {}
}
function getStaticMethods(cl) {
return Object.getOwnPropertyNames(cl)
}
console.log(getStaticMethods(Hi))
// => [ 'length', 'prototype', 'my_static_method', 'name' ]
class ClassWithStaticMethod {
static staticProperty = 'someValue';
static staticMethod() {
return 'static method has been called.';
}
static {
console.log('Class static initialization block called');
}
}
console.log(ClassWithStaticMethod.staticProperty);
// output: "someValue"
console.log(ClassWithStaticMethod.staticMethod());
// output: "static method has been called."
//------------------syntex-------------------------
static methodName() { /* ... */ }
static propertyName [= value];
// Class static initialization block
static {
}
class ClassWithStaticMethod {
static staticMethod() {
return 'static method has been called.';
}
}
console.log(ClassWithStaticMethod.staticMethod());
// expected output: "static method has been called."
// static in class javascript
// Static class methods are defined on the class itself.
// You cannot call a static method on an object, only on an object class.
class Car {
constructor(name) {
this.name = name;
}
static hello() {
return "Hello!!";
}
}
let myCar = new Car("Ford");
// You can call 'hello()' on the Car Class:
document.getElementById("demo").innerHTML = Car.hello();
// But NOT on a Car Object:
// document.getElementById("demo").innerHTML = myCar.hello();
// this will raise an error.