Object.create()和Object.setPrototypeOf
简介
在原型写法中,我们常用Object.create()和Object.setPrototypeOf(),记录一下自己的学习理解
Object.create()
创建一个对象,直接上代码
function SuperClass(name) { this.name = name this.colors = ["red", "blue", "green"] } SuperClass.prototype.getName = function () { console.log(this.name) } const test3 = Object.create(new SuperClass("JJ"), { a: { value: 10, }, b: { value: 20, writable: false, }, name:{ value:"TT" } }) test3.getAB = function(){ return this.a + this.b }
通过下图可以看出,他的结果是创建了一个继承于SuperClass的新对象,但是细心可以发现,__proto__中少了一个constructor
使用其作为一个过渡函数实现继承
function SuperClass(name) { this.name = name this.colors = ["red", "blue", "green"] } SuperClass.prototype.getName = function () { return this.name } function SubClass(name, time) { SuperClass.call(this, name) this.time = time } // 为了不让SuperClass构造两遍,所以用空对象来过渡一下 SubClass.prototype = Object.create(SuperClass.prototype)
const test = new SubClass("TT", 2014)
此时,还是缺少了一个constructor,可以手动补充,SubClass.prototype.constructor = SubClass,然后在进行实例化
或使用Object.setPrototypeOf()来解决
Object.setPrototypeOf()
Object.setPrototypeOf就是字面意思,设置XXX的Prototype原型,所以上述可以将SubClass的原型设置为SuperClass的原型
function SuperClass2(name) { this.name = name this.colors = ["red", "blue", "green"] } SuperClass2.prototype.getName = function () { console.log(this.name) } function SubClass2(name, time) { SuperClass.call(this, name) this.time = time } Object.setPrototypeOf(SubClass2.prototype, SuperClass2.prototype) SubClass2.prototype.getTime = function(){ console.log(this.time) } const test2 = new SubClass2("TT", 2014)
如下图,看起来是不是正常多了