首页 > 编程语言 > 详细

[Javascript] Working with Static Properties on a Class

时间:2019-12-08 00:18:51      阅读:80      评论:0      收藏:0      [点我收藏+]

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

 

[Javascript] Working with Static Properties on a Class

原文:https://www.cnblogs.com/Answer1215/p/12003897.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!