【JavaScript手撕代码】Object.create()

Object.create()

详解

Object.create() 方法能够创建一个新对象,并让已有的对象为新对象提供__proto__
语法: Object.create(proto, [propertiesObject])
  - proto: 新创建对象的原型对象,该对象的属性会继承给被创建的对象
  - prototiesObject(可选): 创建的对象的自身定义的可枚举属性, 例如num: { value: 10 }obj:{ value: false }如果设置了get和set, 那么不能再设置value和writable中任意一个,否则会报错Invalid property descriptor. Cannot both specify accessors and a value or writable attribute
异常: 如果propertiesObject参数是null非原始包装对象,则抛出一个 TypeError 异常。
返回值: 新的对象,新对象的[[Prototype]]即传入的__proto__参数
使用:

const oldObj = {
	name:  'test',
	child: {
		name: 'create'
	}
}

const newObj = Object.create(oldObj, {
	'keyName':{
		value: '初始化赋值',
		writable: true,            // 是否可修改
		configurable: true,        // 是否可删除
		enumerable: true,          // 是否是否可以用for...in...枚举
		/* 如果设置get和set, 那么不能再设置value和writable中任意一个 */
		get: function(){/**/},     // getter
		set: function(value){/**/} // setter  
	}
})

在这里插入图片描述

显然我们可以使用这个API实现继承。
并且,当我们使用Object.create(null)创建对象,会得到一个非常干净的对象,没有任何的属性,不用担心自主定义方法时会覆盖原型链上的同名方法

手写

通过上面的详解,我们差不多明白了Object.create()的内部思路,那么手写就很简单了

方法一

Object.prototype.myCreate = function(proto, propertiesObject=undefined){
	if( typeof proto!== 'object' && typeof proto!=='function' ){
		throw new TypeError(`The passed in prototype must be an object or null: ${proto}`)
	}
	if( propertiesObject === null ){
		throw new TypeError(`Cannot convert undefined or null to object`)
	}

	const newObj = {}
	Object.setPrototypeOf(newObj, proto) // 使用Object.setPrototypeOf()方法设置原型
	
	if( typeof propertiesObject != 'undefined' ){
		Object.defineProperties(newObj, propertiesObject)
	}
	
	return newObj
}

检验:
在这里插入图片描述

方法二:

我们使用构造函数来实现一下

Object.prototype.myCreate = function(proto, propertiesObject=undefined){
	if( typeof proto!== 'object' && typeof proto!=='function' ){
		throw new TypeError(`The passed in prototype must be an object or null: ${proto}`)
	}
	if( propertiesObject === null ){
		throw new TypeError(`Cannot convert undefined or null to object`)
	}
	
	function fn(){};
	fn.prototype = proto;
	fn.prototype.constructor = fn
	if( typeof propertiesObject != undefined ){
		Object.defineProperties(fn, propertiesObject)
	}

	return new fn()
}

检验:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

六时二一

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值