how to use javascript Object.defineProperty

前端 未结 10 1224
不知归路
不知归路 2020-11-29 14:21

I looked around for how to use the Object.defineProperty method, but couldn\'t find anything decent.

Someone gave me this snippet of code:

Object.def         


        
10条回答
  •  伪装坚强ぢ
    2020-11-29 14:56

    import { CSSProperties } from 'react'
    import { BLACK, BLUE, GREY_DARK, WHITE } from '../colours'
    
    export const COLOR_ACCENT = BLUE
    export const COLOR_DEFAULT = BLACK
    export const FAMILY = "'Segoe UI', sans-serif"
    export const SIZE_LARGE = '26px'
    export const SIZE_MEDIUM = '20px'
    export const WEIGHT = 400
    
    type Font = {
      color: string,
      size: string,
      accent: Font,
      default: Font,
      light: Font,
      neutral: Font,
      xsmall: Font,
      small: Font,
      medium: Font,
      large: Font,
      xlarge: Font,
      xxlarge: Font
    } & (() => CSSProperties)
    
    function font (this: Font): CSSProperties {
      const css = {
        color: this.color,
        fontFamily: FAMILY,
        fontSize: this.size,
        fontWeight: WEIGHT
      }
      delete this.color
      delete this.size
      return css
    }
    
    const dp = (type: 'color' | 'size', name: string, value: string) => {
      Object.defineProperty(font, name, { get () {
        this[type] = value
        return this
      }})
    }
    
    dp('color', 'accent', COLOR_ACCENT)
    dp('color', 'default', COLOR_DEFAULT)
    dp('color', 'light', COLOR_LIGHT)
    dp('color', 'neutral', COLOR_NEUTRAL)
    dp('size', 'xsmall', SIZE_XSMALL)
    dp('size', 'small', SIZE_SMALL)
    dp('size', 'medium', SIZE_MEDIUM)
    
    export default font as Font

提交回复
热议问题