JS对象继承的几种方式 深碍√TFBOYSˉ_ 2021-11-17 12:54 355阅读 0赞 # 背景 # 在学习的过程中学到的知识,在此分享给大家,同时也给自己记录一下下 # 1. 原型链继承 # 例子: Grand.prototype.lastName = "Wang"; function Grand(){ } Father.prototype = new Grand(); Father.prototype.age = 50; function Father(){ } Son.prototype = new Father(); function Son(){ } let s1 = new Son(); console.log(s1.lastName) // Wang console.log(s1.age) // 50 不足之处:过多的继承了没用的属性。例如上例中s1本来只想继承lastName,但是将父亲的原型上的age属性也继承过来了 # 2. 借用构造函数 # 例子: function Person(name,age){ this.name = name; this.age = age; } function Student(name,age,school){ Person.call(this,name,age); this.school = school; } let s1 = new Student("张三",18,"某某大学") 利用call改变this指向,以达到借用构造函数的目的 不足之处:每次构造都要多走一个函数,并且不能拿借用构造函数的原型 # 3. 共享原型 # 例子: Person.prototype.action = "吃" function Person(){ } function Student(){ } Student.prototype = Person.prototype let s1 = new Student() console.log(s1.action) // 吃 Student.prototype.action = "学习" console.log(Person.prototype.action)// 学习 不足之处:不能随便改动自己的原型,因为会影响到自己继承对象的原型 # 4.圣杯模式 # 例子: function inherit(Target, Origin){ function F(){ } F.prototype = Origin.prototype; Target.prototype = new F(); Target.prototype.constructor = Target; Target.prototype.uber = Origin.prototype; } Person.prototype.action = "吃" function Person(){ } function Student(){ } inherit(Student,Person) let s1 = new Student(); console.log(s1.action); //吃 Student.prototype.action = "学习"; console.log(Person.prototype.action)//吃 当然以上几种继承都是指ES6之前的,ES6提出了类(class)的概念,所以相应的也出现了类的继承,使得对象的继承更加简单,在此仅做简单记录: class Student extends Person{ } 如果觉得文章有帮到你的话,帮我点个赞吧,如果觉得有用建议收藏起来,偶尔看一下,感觉对象的继承在面试大厂的时候还是经常会问的,加油~
还没有评论,来说两句吧...