1、typescript

  1. interface Shape {
  2. draw: () => void;
  3. }
  4. class Rectangle implements Shape {
  5. draw() {
  6. console.log('draw Rectangle')
  7. }
  8. }
  9. class Square implements Shape {
  10. draw() {
  11. console.log('draw Square')
  12. }
  13. }
  14. class Circle implements Shape {
  15. draw() {
  16. console.log('draw Circle')
  17. }
  18. }
  19. class ShapeMaker {
  20. private circle: Shape;
  21. private rectangle: Shape;
  22. private square: Shape;
  23. constructor() {
  24. this.circle = new Circle();
  25. this.rectangle = new Rectangle();
  26. this.square = new Square();
  27. }
  28. drawCircle() {
  29. this.circle.draw();
  30. }
  31. drawRectangle() {
  32. this.rectangle.draw();
  33. }
  34. drawSquare() {
  35. this.square.draw();
  36. }
  37. }
  38. const maker = new ShapeMaker()
  39. maker.drawCircle()
  40. maker.drawRectangle()
  41. maker.drawSquare()

2、javascript (apply)

这里借一下aplly方法来模拟一下

  1. var _type = 'string'
  2. Object.prototype.toString.apply(_type) // "[object String]"
  3. var _type = 123
  4. Object.prototype.toString.apply(_type) // "[object Number]"
  5. var _type = null
  6. Object.prototype.toString.apply(_type) // "[object Null]"