es6的继承

// es5/6继承的区别
// es5继承
// function Parent (name, age) {
//   this.name = name;
//   this.age = age;

//   this.introduce = function () {
//     console.log("Hi, my name is " + this.name + " and I am " + this.age + " years old.");
//   };
// }
// Parent.prototype = { proto: 0 }
// var parentObject = new Parent();
// parentObject.introduce()

// // function children (name, age) {
// //   this.name = name;
// //   this.age = age;
// //   this.introduce = function () {
// //     console.log("Hi, my name is " + this.name + " and I am " + this.age + " years old.")
// //   }
// // }
// function children (name, age) {
//   Parent.call(this, name, age);
//   // console.log('children.prototype', children.prototype, children.proto);
//   // children.prototype = Object.create();
// }
// function inheritPrototype (parent, children) {
//   children.prototype = Object.create(parent.prototype)
//   children.prototype.constuctor = children;
// }
// // children.prototype = Object.create(Parent.prototype);
// // children.prototype.constuctor = children;

// var childrenObj = new children(11, 22);
// childrenObj.introduce();

console.log('第二种写法');
class Parent {
  constructor(name) {
    this.name = name;
    console.log("Hi, my name is " + this.name);
  }
}
var parent = new Parent('p');
console.log(parent, parent.name);

class Child {
  constructor(name) {
    this.name = name;
    console.log("Hi, my name is " + this.name);
  }
}
var child = new Child('c');
console.log(child, child.name);

class Child2  {
  constructor(name2) {
    this.name2 = name2;
  }
}
var child2 = new Child2('c2');
console.log(child2, child2.name);

可以看出,子类通过extends的方式继承父类的属性,方法,在创建子实例时,需先使用父构造函数创造对象,this才有指向的对象,再添加子类的属性方法。

为什么子类的构造函数,一定要调用super()?原因就在于 ES6 的继承机制,与 ES5 完全不同。ES5 的继承机制,是先创造一个独立的子类的实例对象,然后再将父类的方法添加到这个对象上面,即“实例在前,继承在后”。

ES6 的继承机制,则先创建一个空的对象,来承接父类的属性和方法,再将该对象作为子类的实例,即“继承在前,实例在后”。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值