JavaScript中Object.create()方法的实例用法详解
作者:青柠时间:2026-10-24 16:43:51浏览:631
本文详细解析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()方法实例用法的详细介绍,更多相关技术内容欢迎查阅本站往期文章或继续阅读后续教程,感谢您的支持!
作者最新文章
ES6模块化中js文件怎么用import和export交互
2026-11-05 17:00:48
JS读取本地文件时报错或无响应的常见原因
2026-11-05 16:32:31
let、const与var的区别:JavaScript变量声明最佳实践
2026-11-05 14:16:38
JS中直接定义静态二维数组的字面量写法
2026-11-05 14:16:08
JS 怎么查找字符串中所有匹配项的位置
2026-11-05 14:15:53
