JavaScript 对象(Objects) 方法

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

语法:

Object.create(prototype[, propertiesObject])

参数

prototype:它是原型对象,必须从中创建新对象。

propertiesObject:可选参数。它指定要添加到新创建的对象的可枚举属性。

返回值

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

浏览器支持

chrome是的
edge是的
firefox是的
opera是的

示例

下面介绍一些例子帮助理解该方法的使用。

示例1

<script>
const people = {
  printIntroduction: function ()
   {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  }
};
const me = Object.create(people);
me.name = "Marry"; 
me.isHuman = true; 
me.printIntroduction();
</script> 

输出:

"My name is Marry. Am I human? true"

示例2

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

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

输出:

"franco"

示例3

<script>
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);
</script>

输出:

"fruit"
"Winter"
"Winter"