手写一个new

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>手写一个new</title>
	</head>
	<body>
		<script>
			// 1.创建一个新的对象
			// 2.继承父类的方法】
			// 3.添加父类的属性到新对象上并初始化,保存方法的执行结果
			// 4.如果执行执行结果有返回值并且是一个对象,则返回执行的对象,否则返回新的对象
			function _new(obj, ...rest) {
    
    
				const newObj = Object.create(obj.prototype)
				const result = obj.apply(newObj, rest)
				//instanceof 需要注意的是由于数组也是对象,因此用 arr instanceof Object 也为true。
				//typeof 数组和null均为对象
				return Object.prototype.toString.call(result) === '[object Object]' ? result : newObj
			}

			function _new2() {
    
    
				// 1.创建一个新对象
				const obj = new Object()
				// 2.获取构造函数
				const Con = [].shift.call(arguments)
				// 3.连接到原型
				obj.__proto__ = Con.prototype
				// 4.执行构造函数,绑定this
				let result = Con.apply(obj, arguments)
				// 确保 new 出来的是个对象
				//instanceof 需要注意的是由于数组也是对象,因此用 arr instanceof Object 也为true。
				//typeof 数组和null均为对象
				return Object.prototype.toString.call(result) === '[object Object]' ? result : obj
			}

			function Person(firtName, lastName) {
    
    
				this.firtName = firtName;
				this.lastName = lastName;
			}
			const tb = new Person('Chen', 'Tianbao');
			console.log(tb);

			const tb2 = _new2(Person, 'Chen', 'Tianbao');
			console.log(tb2)
		</script>
	</body>
</html>
代码中使用到了apply,call;这里可以简单说下apply,call,bind的区别

apply与call基本一致,区别在于传参方式,apply参数是一个数组或类数组,call是直接一个一个传递
fn.apply(obj,[1,2,3,4])
fn.call(obj,1,2,3,4)
call语法与bind一模一样,区别在于立即执行还是等待执行,bind不兼容IE6~8
fn.call(obj, 1, 2); // 改变fn中的this,并且把fn立即执行
fn.bind(obj, 1, 2); // 改变fn中的this,并且把fn不立即执行

猜你喜欢

转载自blog.csdn.net/Admin_yws/article/details/125065691