JS实现继承的几种方式
结论:组合继承是最好的继承方式
详见原文地址:https://www.cnblogs.com/humin/p/4556820.html
补充一个复杂点的组合继承例子:
function Person(name, age) { this.name = name; this.age = age; } Person.prototype.hi1 = function() { console.log("Hi,my name is " + this.name + ",I'm " + this.age + " years old now."); } Person.prototype.LEGS_NUM = 2; Person.prototype.ARMS_NUM = 2; Person.prototype.walk = function() { console.log(this.name + " is walking..."); } function Student(name, age, className) { Person.call(this, name,age); //注意call和apply的区别call第二个参数必须一个一个(可以改顺序)传而apply则可以传入一个数组,二者作用一致,都是把Person(即this)绑定到Student,这时候Student具备了Person的属性和方法。或者说Sdutent继承了Person的属性和方法。 // Person.apply(this,arguments); //call 和 apply 都是为了改变某个函数运行时的 context 即上下文而存在的,换句话说,就是为了改变函数体内部 this 的指向。 this.className = className; } Student.prototype = Object.create(Person.prototype) //用Object.create而不是直接赋值可以在Student类里写自己的方法且不会在父类里面增加此方法 Student.prototype.constructor = Student; //这里是让Student的指向它本身如果不写就会指向Person Student.prototype.hi = function() { console.log("Hi,my name is " + this.name + ",I'm " + this.age + " years old now,and from " + this.className + "."); } Student.prototype.learn = function(subject) { console.log(this.name + " is learning " + subject + " at " + this.className + "."); } function StudentSon(name,age){ Student.call(this, name, age); } StudentSon.prototype = Object.create(Student.prototype) // StudentSon.prototype.constructor = StudentSon; // StudentSon.prototype.hi = function() { console.log("Hi, son name is " + this.name + ",I'm " + this.age + " years old now."); } //test var Jim=new Student('jim',24,'Class 3,Grade 4'); Jim.hi(); console.log(Jim.LEGS_NUM); Jim.hi1() Jim.walk(); Jim.learn("JavaScript!"); console.log("---------------") var hu=new StudentSon("hu",2); hu.hi();