破解JavaScript高级玩法:笔记

61 阅读1分钟
  1. 对象的认知升级

对象的属性遍历

属性的类型

  • 普通属性
  • 不可枚举属性
  • 原型属性
  • Symbol属性(ES6)
  • 静态属性(特别)

属性的遍历方式

  1. for in
  2. Object.Keys
  3. Object.Values
  4. Object.getOwnPropertyNames
  5. Object.getOwnPropertySymbols
  6. Reflect.ownKeys(非常强大)
  7. for of(ES6特别)

图览

c16e2034430c8d8df9dab353b26fcab.jpg

获得原型上的所有属性

  1. for in
  2. 递归
  3. 剔除内置属性

代码

class Grand {
  gName = 'Grand'
  gGetName() {
    return this.gName
  }
}

Grand.prototype[Symbol.for('gAge')] = 'G-12'

class Parent extends Grand {
  pName = '123'
  pGetName () {
    return this.pName
  }
}

Parent.prototype[Symbol.for('pAge')] = 'G-11'

class Child extends Parent {
  cName = '123'
  cGetName() {
    return this.cName
  }
}

const child = new Child()

let result = []

function logAllProperties (instance) {
  if (instance === null) return
  let proto = instance.__proto__

  while (proto) {
    result.push(...Reflect.ownKeys(proto))
    proto = proto.__proto__
  }
}

logAllProperties(child)

console.log(result)
/**
 * [
    "constructor",
    "cGetName",
    "constructor",
    "pGetName",
    null,
    "constructor",
    "gGetName",
    null,
    "constructor",
    "__defineGetter__",
    "__defineSetter__",
    "hasOwnProperty",
    "__lookupGetter__",
    "__lookupSetter__",
    "isPrototypeOf",
    "propertyIsEnumerable",
    "toString",
    "valueOf",
    "__proto__",
    "toLocaleString"
]
 */

图片

image.png