Object.create用法
用法: Object.create(object, [,propertiesObject])
创建一个新对象,继承object的属性,可添加propertiesObject添加属性,并对属性作出详细解释(此详细解释类似于defineProperty第二个参数的结构)
var banana= { color: 'yellow', getColor: function(){ return this.color } }
//创建对象sub_banana var sub_banana= Object.create(banana) console.log(sub_banana.color) //yellow console.log(sub_banana.getColor()) //yellow
添加propertiesObject
"use strict" var banana= { color: 'yellow', getColor: function(){ return this.color } } var sub_banana= Object.create(banana, {
//添加taste属性 taste: {
//详细解释 writeable: false, get: function(){ console.log('getTaste') return 'good' } },
//添加weight
weight: {
value: 600
} }) console.log(sub_banana.color) console.log(sub_banana.getColor()) console.log(sub_banana.taste) //good
console.log(sub_banana.weight) //600 sub_banana.taste= 'bad' //报错,writeable为false不可改变
此方法也常用于创建对象实例
function theSuper(_a){ this.a= 100 } theSuper.prototype.getA= function(){ return this.a } //继承prototype var sub1= Object.create(theSuper.prototype)
//继承prototype而不是构造函数内的值 console.log(sub1.a) //undefined sub1.a= 100 console.log(sub1.getA()) //100
那么,此方法与new obj()的区别在哪?
Object.create的实现核心代码:
Object.create = function (o) { var F = function () {}; F.prototype = o; return new F(); };
可见: 创建函数,将传递的对象赋给函数的prototype,再返回函数实例。
new obj()的核心实现代码:
var o1 = new Object(); o1.[[Prototype]] = Base.prototype; Base.call(o1);
创建对象,将被继承对象的prototype赋给此对象,并且调用被继承对象的方法来为其初始化。(因此new obj()不仅能继承prototype,也能继承构造函数内属性)