共计 1249 个字符,预计需要花费 4 分钟才能阅读完成。
Object.create()的定义
参数
Object.create(proto,[propertiesObject])
proto: 新创建对象的原型对象
propertiesObject: 可选。要添加到新对象的可枚举(新添加的属性是其自身的属性,而不是其原型链上的属性)的属性。
返回值
一个新对象,带着指定的原型对象和属性。
实例
const person = { | |
isHuman: false, | |
printIntroduction: function () {console.log(123); | |
} | |
}; | |
const me = Object.create(person,{ | |
// foo 会成为所创建对象的数据属性, 且 foo 必须为一个对象;可设置新对象的 foo 属性的可读性,可配置性以及值 | |
foo: { | |
writable:true, | |
configurable:true, | |
value: "hello" | |
} | |
}); | |
me.name = "Matthew"; // "name" is a property set on "me", but not on "person" | |
me.isHuman = true; // inherited properties can be overwritten | |
console.log(me) |
new Object()
通过构造函数来创建对象, 添加的属性是在自身实例下。
Object.create() es6 创建对象的另一种方式,可以理解为继承一个对象, 添加的属性是在原型下。:
var a = {rep : 'apple'} | |
var b = new Object(a) | |
console.log(b) // {rep: "apple"} | |
console.log(b.__proto__) // {} |
Object.create()
var a = {rep: 'apple'} | |
var b = Object.create(a) | |
console.log(b) // {} | |
console.log(b.__proto__) // {rep: "apple"} |
Object.create(null)与 Object.create({})还是有区别的
先看看我们经常使用的 {} 创建的对象是什么样子的
var o = {a:1}; | |
console.log(o) |
再看看使用 Object.create()创建对象:
var o = Object.create(null,{ | |
a:{ | |
writable:true, | |
configurable:true, | |
value:'1' | |
} | |
}) | |
console.log(o) |
我们再把上面的例子改为{}
var o = Object.create({},{ | |
a:{ | |
writable:true, | |
configurable:true, | |
value:'1' | |
} | |
}) | |
console.log(o) |
创建的对象和使用 {} 创建对象已经很相近了,但是还是有一点区别:多了一层 proto 嵌套。
我们最后再来改一下:
var o = Object.create(Object.prototype,{ | |
a:{ | |
writable:true, | |
configurable:true, | |
value:'1' | |
} | |
}) | |
console.log(o) |
正文完
发表至: javascript
2019-09-12