1、原型继承
实现:
function Super(){ this.a=1 } Super.prototype.say = function(){ console.log(‘hhh’) } function Sub(){} Sub.prototype = new Super() const test = new Sub() console.log( test.say() )// hhh
优点:通过原型继承多个引用类型的属性和方法
缺点:Sub原型变成了Super的实例,如果Super的实例某个属性是引用值,该引用值就会被应用到所有Sub创建的实例中去,会有污染问题。如下
function Super(){ this.a=[1,2] } function Sub(){} Sub.prototype = new Super() const test1 = new Sub() test1.a.push(3) console.log(test1.a)// [1,2,3] const test2 = new Sub() console.log(test2.a)// [1,2,3]
2、盗用构造函数
实现:构造函数模式+call
function Super = function(){ this.a = 1 } function Sub = function(){ Super.call(this) this.b = 2 } const test = new Sub()
优点:每个实例都会有自己的a属性,哪怕是引用值也不会被污染
缺点:Super构造函数中的方法在每个实例上都要创建一遍(除非该方法声明提到全局);Sub的实例无法访问Super原型上的方法<