js中实现继承的方式

2020-02-11  本文已影响0人  五四青年_4e7d

原型继承

//优点:简单
//缺点:属性被实例共享,不能向父类传递参数
function Parent(){}
function Child(){}
Child.prototype = new Parent()

借用构造函数继承

//优:避免共享;可以向父传参  缺:方法在构造函数中定义,创建实例都会创建一遍
function Parent(name){}
function Child(){
    Parent.call(this,name) 
}

组合继承:

function Parent (name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
}
Parent.prototype.getName = function () { return this.name; }

function Child (name, age) {
  Parent.call(this, name);  
  this.age = age;
}
Child.prototype = new Parent();

上一篇 下一篇

猜你喜欢

热点阅读