Before talking about it, let's review several ways to create objects and the differences between and Object
, new Object()
andObject.create
①: Create objects using literals
let person = {
name: 'nick'
}
②: Constructor-style creation of objects
let person = new Object({
name: 'nick' })
③: Objecr.create
Create objects
let person = Object.create(Object.prototype, {
name: 'nick',
enumerable: true, // 可枚举
configurable: true, // 可通过Object.definePrototype修改其配置
writable: true // 可重写
})
There is essentially no difference between the first and second types. They are just simplified writing methods and let’s talk about the differences between the second and third types:
new Object()
Object
The prototype of the constructor will be inherited in the process . We can see new
what happens in the process:
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
}
We can see above that the prototype is inherited Object
, and Object.create
the first parameter is just to set the prototype. The second parameter can bind its own properties and methods, and set its property descriptor. Next, we will study the difference between Objecr.create
andObject.setProrotypeOf
Note: These are all ES5
new methods proposed by
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)
By printing the results, we can see that Student
the original prototypes and constructors have all been replaced:
Let's try again Object.setPrototypeOf
method
Object.setPrototypeOf(Student.prototype, Person.prototype)
console.log(Student.prototype)
As you can see by printing, the current prototype object is retained, and new prototype objects are added based on the current prototype object.prototype
expand:
- 1. Get the prototype of the object:
xx.getPrototypeOf()
- 2. Get the property descriptor of the object:
Object.getOwnPropertyDescriptor(xx, 'xx')