new操作符干了啥(手写new操作符)

new操作符干了啥(手写new操作符)

在JS中,new操作符用于创建一个新对象并调用一个函数来初始化对象,下面是手写实现new操作符的方法:

// 传入构造函数
const myNew = (constructor) => {
    
    
	// 1、创建一个空对象 {}
	const obj = {
    
    }
	// 2、让对象的__proto__指向构造函数的prototype
	obj.__proto = constructor.prototype
	// 3、调用构造函数,并使用该对象作为this
	const res = constructor.apply(obj)
	// 4、返回该对象
	return obj
}
// 传入构造函数的参数 args
const myNew = (constructor, ...args) => {
    
    
	// 1、创建一个空对象 {}
	const obj = {
    
    }
	// 2、让对象的__proto__指向构造函数的prototype
	obj.__proto = constructor.prototype
	// 3、调用构造函数,并使用该对象作为this
	const res = constructor.apply(obj, args)
	// 4、返回
	return res instanceof Object ? res : obj // 否则为undefined
}

在这里插入图片描述
在这里插入图片描述

为什么最后要判断返回什么?

这里就要说到JS构造函数返回值的问题了

  • 构造函数本不应该有返回值,实际返回的就是此构造函数的实例化对象
  • js中构造函数可以有返回值,也可以没有,没有事和正常函数一样,返回实例化对象
  • 返回值是非引用类型,如基本类型(string, number, boolean, null, undefined)则与无返回值相同
  • 返回值是引用类型,则实际返回的是这个引用对象

在这里插入图片描述


在这里插入图片描述
再看看下面这个:

// String(‘foo’) 返回的是string类型,非引用类型,所以不会影响,因为构造函数没有属性,返回一个空对象
console.log( 'foo' == new function(){
    
     return String('foo') } )      // false
// new String(‘foo’) 返回的是字符串对象,所以会返回该字符串对象
console.log( 'foo' == new function(){
    
     return new String('foo') } )  // true

猜你喜欢

转载自blog.csdn.net/weixin_44582045/article/details/132531829
今日推荐