码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] Working with Static Properties on a Class

时间:2019-12-08 01:07:20      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:sel   less   obj   tac   over   console   abi   return   sso   

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

标签:sel   less   obj   tac   over   console   abi   return   sso   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!