美文网首页
Object.create()

Object.create()

作者: hszz | 来源:发表于2021-11-04 18:55 被阅读0次

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/create
https://www.jianshu.com/p/28d85bebe599

简介

  • Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__

简单的来说,假如传入一个对象a,生成一个对象b,就会有b.__proto__ = a

实现原理

Object.create() 的实现原理如下

function prodObject(obj) {
    function F() {

    }
    F.prototype = obj
    return new F()
}
let aa = {
    color: 'red',
    city: 'china-gz'
}
console.log('aa', aa) // aa { color: 'red', city: 'china-gz' }

let a1 = prodObject(aa)
console.log('a1', a1) // a1 {}
console.log(a1.color) // red

let a2 = Object.create(aa)
console.log('a2', a2) // a2 {}
console.log(a2.color) // red

console.log(a1.__proto__ === a2.__proto__) // true
image.png
  • 此时可以看到a1和a2本身时没有任何属性的,但是它们会通过原型链__proto__向上查找。

语法 Object.create(proto,[propertiesObject])

  • proto 该参数是一个对象, 会作为新对象的原型对象
  • propertiesObject 该参数是一个属性描述对象,它所描述的对象属性,会添加到新对象中,作为该新对象自身的属性。
  • value: 设置属性的值, 默认值为undefined
  • writable: 设置属性值是否可写, 默认值为true
  • enumerable: 设置属性是否可枚举, 即是否允许使用 for/in 语句或 Object.keys() 函数遍历访问, 默认值 true
  • configurable: 设置是否可设置属性特性, 默认为true, 如果为false, 将无法删除属性, 不能够修改属性值, 也不能修改属性的属性的描述符的值
  • get: 取值函数, 默认为undefined
  • set: 存值函数, 默认为undefined
let a3 = Object.create(aa, {
    lastName: {
        value: 'hszz', 
        writable: true,
        enumerable: true,
        configurable: true 
      }
})
console.log('a3', a3)
console.log(a3.lastName)
image.png
for(let key in a3) {
    console.log(key)
    console.log(a3.hasOwnProperty(key))
}
image.png
  • 通过 propertiesObject 添加的属性会加入到新对象本身。

__proto__ 属性

  • js继承是通过原型链实现的。__proto__属性用来读取或设置当前对象的prototype对象。目前只有浏览器环境必须部署有这个属性,其他运行环境不一定要部署,因此不建议使用这个属性,而是使用下面这些来 Object.setPrototypeOf()(写操作)Object.getPrototypeOf()(读操作)Object.create()(生成操作)来代替。
Object.create()在上方已经介绍过了
Object.setPrototypeOf()
  • 语法 Object.setPrototypeOf(object, prototype)
  • 用来设置对象的原型对象。
Object.getPrototypeOf()
  • 语法 Object.getPrototypeOf(object)
  • 用于读取一个对象的原型对象;
let a = {
    color: 'red',
    size: 100,
}

let b = {
    withd: 200,
    arr: [1, 2, 3],
}
// b.__proto__ = a // 不推荐使用
Object.setPrototypeOf(b, a) // 推荐使用
console.log('b',b)

// console.log(b.__proto__ === a) // 不推荐使用
console.log(Object.getPrototypeOf(b) === a) // 推荐使用
image.png

相关文章

网友评论

      本文标题:Object.create()

      本文链接:https://www.haomeiwen.com/subject/qyvkzltx.html