Object.setPrototypeOf 与 Object.create() 的区别

2023-11-01

在讲之前,我们先回顾下创建对象的几种方式,并且Objectnew Object()Object.create 的区别

①:字面量方式创建对象

let person = {
  name: 'nick'
}

②:构造函数式创建对象

let person = new Object({ name: 'nick' })

③:Objecr.create 创建对象

let person = Object.create(Object.prototype, { 
	name: 'nick',
    enumerable: true, // 可枚举
    configurable: true, // 可通过Object.definePrototype修改其配置 
    writable: true // 可重写
})

第一和第二种本质上没任何区别,只是简化写法,说下第二种和第三种的区别:

new Object() 的过程中会继承 Object 构造函数的原型,我们可以看下 new 的过程发生了什么:

function MyNew(fun) {
	// 创建一个对象
	let obj = {}
	// 获取参数,这里要给参数arguments绑定Array原型上的方法,并且排除第一个参数fun
	let args = Array.prototype.slice.call(arguments, 1)
	// 执行函数,绑定this,这里用call也一样,只不过参数类型不一样
	let res = fun.apply(obj, args)
	// 绑定原型,这里也可以用Object.setPrototypeOf()来绑定,也可以使用 Reflect.setPrototypeOf() 来绑定
	obj.__proto__ = fun.prototype
	// Object.setPrototypeOf(obj, fun.prototype)
	// Reflect.setPrototypeOf(obj, fun.prototype)
	// 判断是否返回对象,反之返回生成的对象
	return Object.prototype.toString.call(res) === '[object Object]' ? res : obj
}

以上我们可以看到,继承了Object的原型,而Object.create第一个参数恰恰是设置原型,第二个参数可以绑定自身的属性和方法,并且设置其属性描述符,接下来,我们研究下 Objecr.createObject.setProrotypeOf 的区别

备注:都是 ES5 提出的新方法

function Student() {
  this.name = '小明'
}

Student.prototype.getName = function () {
  return this.name
}

function Person() {
  this.age = 18
}

Person.prototype.getAge = function () {
  return this.age
}

Student.prototype = Object.create(Person.prototype)

console.log(Student.prototype)

通过打印结果,我们可以看到 Student 原有的原型以及构造函数全部被替换:

在这里插入图片描述
我们再尝试 Object.setPrototypeOf 方法

Object.setPrototypeOf(Student.prototype, Person.prototype)

console.log(Student.prototype)

通过打印可以看到,保留当前的原型对象,并且基于当前的原型对象又添加了新的 prototype

在这里插入图片描述
拓展:

  • 1. 获取对象的原型:xx.getPrototypeOf()
  • 2. 获取对象的属性描述符:Object.getOwnPropertyDescriptor(xx, 'xx')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Object.setPrototypeOf 与 Object.create() 的区别 的相关文章

随机推荐