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

【Javascript】手写运算符new创建实例并实现js继承 #8

Open
AwesomeDevin opened this issue Apr 28, 2019 · 0 comments
Open

Comments

@AwesomeDevin
Copy link
Owner

AwesomeDevin commented Apr 28, 2019

new 运算符

在js中,new()常被用来创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例
本文,主要讲如何手写function new创建实例并实现js继承

对于想彻底捋清楚new做了哪些操作的同学,可以查看我的这篇文章:

【Javascript】彻底捋清楚javascript中 new 运算符的实现

手写实现 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    
}

使用 subNew() 创建实例并对比new()

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

现在我们来尝试使用subNew()实现js继承

(继承的底层实原理其实是通过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

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