Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new模拟实现 #9

Open
conan1992 opened this issue Jun 2, 2020 · 0 comments
Open

new模拟实现 #9

conan1992 opened this issue Jun 2, 2020 · 0 comments

Comments

@conan1992
Copy link
Owner

conan1992 commented Jun 2, 2020

new原理

定义: new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象类型之一;

  • new的结果是生成一个对象
  • 生成的对象原型指向构造函数的原型
  • 构造函数里的this指向生成的对象

初步实现

function foo(){
	var obj = new Object();
	var constructor = Array.prototype.shift.call(arguments)//构造函数
	
        // 链接到原型,obj 可以访问到构造函数原型中的属性
	obj.__proto__ = constructor.prototype;
	
        // 绑定 this 实现继承,obj 可以访问到构造函数中的属性
        constructor.apply(result, arguments);
	return  obj;
}

思考

当构造函数有返回值时呢?
如果返回值是一个对象,我们就返回这个对象,如果没有,我们返回生成的对象。
最终版

function foo(){
	var obj = new Object();
	var constructor = Array.prototype.shift.call(arguments)//构造函数
	

	obj.__proto__ = constructor.prototype;
	var result = constructor.apply(result, arguments);
	return result instanceof Object ? result : obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant