// 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 的继承机制,则先创建一个空的对象,来承接父类的属性和方法,再将该对象作为子类的实例,即“继承在前,实例在后”。