We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
在js中,new()常被用来创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例 本文,主要讲如何手写function new创建实例并实现js继承
【Javascript】彻底捋清楚javascript中 new 运算符的实现
function subNew(){ var obj = {} 将父级的原型prototype指向子级的隐式原型__proto__ obj.__proto__ = Parent.prototype //创建实例的时候传参 var res = Parent.call(obj,...arguments) //当构造函数有return时,返回return值,没有则返回obj{} return typeof(res) === 'object'&&res || obj }
var obj1 = new Constructor() var obj2 = subNew() console.log(new Constructor(123),subNew(123)) console.log(new Constructor({a:123}),subNew({a:123})) console.log(obj1.__proto__,obj2.__proto__,Constructor.prototype)
可以发现 我们已经成功创建了new的实例,并且obj1,obj2的__proto__都指向Constructor的prototype
(继承的底层实原理其实是通过this.fn=Parent&&this.fn(),调用父类函数,改变this指向的同时,也改变了函数的内部对象(即运行时上下文) )
function Parent(sex) { this.sex = sex } Parent.prototype.saySex=function(){ console.log(this.sex) } function Child() { Parent.apply(this,[...arguments]) } function subNew(){ var obj = {} obj.__proto__ = Parent.prototype var res = Parent.call(obj,...arguments) return typeof(res) === 'object'&&res || obj } Child.prototype = subNew() // 等同于 Child.prototype = new Parent() var c=new Child('男'); c.saySex();
Child 继承成功了!!!
如果觉得我的文章对你有帮助,欢迎star我的blog
The text was updated successfully, but these errors were encountered:
No branches or pull requests
new 运算符
对于想彻底捋清楚new做了哪些操作的同学,可以查看我的这篇文章:
【Javascript】彻底捋清楚javascript中 new 运算符的实现
手写实现 new()
使用 subNew() 创建实例并对比new()
可以发现 我们已经成功创建了new的实例,并且obj1,obj2的__proto__都指向Constructor的prototype
现在我们来尝试使用subNew()实现js继承
(继承的底层实原理其实是通过this.fn=Parent&&this.fn(),调用父类函数,改变this指向的同时,也改变了函数的内部对象(即运行时上下文) )
Child 继承成功了!!!
如果觉得我的文章对你有帮助,欢迎star我的blog
The text was updated successfully, but these errors were encountered: