[Javascript] Working with Static Properties on a Class

Classes are syntactic sugar over functions and functions are also referred to as "callable" objects. So it is possible to treat a function like an object and give them key / value properties like objects. The static keyword gives us the ability to assign a key / value property to a class itself, not an instance of that class. This lesson will walk you through using the static keyword and even show how to replicate it with regular functions.

class Retangle{
  static callRectangle(){
    return 'hello world'
  }
}

const myShape = new Rectangle() 
console.log(myShape.callRectangle) // error, you cannot call static prop on instance

But static prop can be called from child class:

function Rectangle(){
}

Rectangle.callRectangle = function(){
  return 'hello world'
}
class Square extends Rectangle {
  static whoAmI(){
    return "Hello, all " + super.callRectangle()
  }
}

console.log(Square.whoAmI()) //Hello, all hello world

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/12003897.html
今日推荐