JavaScript中Object.create()方法的实例用法详解

作者:青柠

时间:2026-10-24

浏览:632

本文详细解析JavaScript中Object.create()方法的用法,通过具体实例展示如何利用现有对象作为原型创建新对象。内容涵盖基本语法、参数说明以及处理值类型与引用类型属性的区别,帮助开发者深入理解原型链继承机制。

文章目录

使用Object.create()方法可以创建一个新对象,并将现有对象指定为该新对象的原型()。

该方法接受两个参数:第一个参数用于指定新对象的原型对象,第二个参数则是用于为新对象添加自有属性的描述符对象。

具体代码示例如下:


// father 对象
let father = {
    name: 'father',
    friend: ['abby', 'bob']
}
 
// 生成新实例对象 child1
let child1 = Object.create(father)
 
// 更改值类型属性
child1.name = '修改了name'
console.log(child1.name) //修改了name
 
// 更改引用类型值
child1.friend.push('chely')
console.log(child1.friend) //[ 'abby', 'bob', 'chely' ]
 
// 生成新实例对象 child2
let child2 = Object.create(father)
console.log(child2.name) //father
console.log(child2.friend) //[ 'abby', 'bob', 'chely' ]

相关知识点扩展:

Object.create()创建方法的实际运行效果展示:


const person = {
  isHuman: false,
  printIntroduction: function() {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  }
};

const me = Object.create(person);

me.name = 'Matthew'; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwritten

me.printIntroduction();
// expected output: "My name is Matthew. Am I human? true"

代码执行后的控制台输出结果:

> "My name is Matthew. Am I human? true"

以上就是关于JavaScript中Object.create()方法实例用法的详细介绍,更多相关技术内容欢迎查阅本站往期文章或继续阅读后续教程,感谢您的支持!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章