Object.create()函数详解

首页 / JavaScript入门教程 / Object.create()函数详解

Object.create()方法用于创建具有指定原型对象和属性的新对象。我们可以通过Object.creates(null)创建没有原型的对象。

语法

Object.create(prototype[, propertiesObject])

参数

prototype   - 它是原型对象,必须从该对象创建新对象。

propertiesObject  - 这是一个可选参数。它指定要添加到新创建对象的可枚举属性。

返回

Object.create()返回具有指定原型对象和属性的新对象。

浏览器支持

Chrome yes
Edge yes
Firefox yes
Opera yes

例子1

const people = {
  printIntroduction: function ()
   {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  }
};
const me = Object.create(people);
me.name = "Marry";//"name" is a property set on "me", but not on "person"
me.isHuman = true;//inherited properties can be overwritten
me.printIntroduction();

输出:

"My name Marry. Am I human? true"

例子2

function fruits() {
        this.name = 'franco';
        }
       function fun() {
        fruits.call(this)
 }

        fun.prototype = Object.create(fruits.prototype);
        const app = new fun();
        console.log(app.name);

输出:

"franco"

例子3

function fruits() {
        this.name = 'fruit';
        this.season = 'Winter';
        }

        function apple() {
        fruits.call(this);
        }

        apple.prototype = Object.create(fruits.prototype);
        const app = new apple();
        console.log(app.name,app.season);
        console.log(app.season);

输出:

"fruit"
 "Winter"
"Winter"

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

赵成的运维体系管理课 -〔赵成〕

Python核心技术与实战 -〔景霄〕

Elasticsearch核心技术与实战 -〔阮一鸣〕

NLP实战高手课 -〔王然〕

重学线性代数 -〔朱维刚〕

To B市场品牌实战课 -〔曹林〕

快手 · 移动端音视频开发实战 -〔展晓凯〕

结构思考力 · 透过结构看表达 -〔李忠秋〕

云时代的JVM原理与实战 -〔康杨〕

好记忆不如烂笔头。留下您的足迹吧 :)