Javascript Object.create()
目录
JavaScript Object.create()方法使用给定对象的原型创建一个新对象。
create()
方法的语法为:
Object.create(proto, propertiesObject)
使用Object
类名称调用create()
方法(它是静态方法)。
create()参数
create()
方法采用:
- proto-该对象应该是新创建的对象的原型。
- propertiesObject (可选)-一个对象,其可枚举的自身属性指定要添加到新创建的对象的属性描述符。这些属性对应于
Object.defineProperties()
的第二个参数。
从create()返回值
- 返回具有指定原型对象和属性的新对象。
注意:如果proto不为null
或Object
,则抛出TypeError
。
示例:使用Object.create()
let Animal = { isHuman: false, sound: "Unspecified", makeSound() { console.log(this.sound); }, }; // create object from Animal prototype let snake = Object.create(Animal); snake.makeSound(); // Unspecified // properties can be created and overridden snake.sound = "Hiss"; snake.makeSound(); // Hiss // can also directly initialize object properties with second argument let properties = { isHuman: { value: true, }, name: { value: "Jack", enumerable: true, writable: true, }, introduce: { value: function () { console.log(`Hey! I am ${this.name}.`); }, }, }; human = Object.create(Animal, properties); human.introduce(); // Hey! I am Jack.
输出
Unspecified Hiss Hey! I am Jack.
推荐阅读: Javascript对象isPrototypeOf()
总计 0 评论