js中es5类的创建继承与es6中类的创建继承
es5类的创建与继承
console.log('寄生组合式继承');
function TheClass(props) {
this.name=props.name||'';
this.grade=props.grade||'';
}
TheClass.prototype.hello=function () {
alert('Hello'+this.name);
};
function createClass(props) {
return new TheClass(props||{});
}
function inherits(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
function TheClassChild(props) {
TheClass.call(this,props);
this.zzz=props.zzz||'';
}
inherits(TheClassChild,TheClass);
TheClassChild.prototype.alertA=function () {
alert(this.zzz);
};
function createTheClassChild(props) {
return new TheClassChild(props||{});
}
var bb=new TheClass({name:'baby',grade:'class1'});
bb.hello();
var cc=new TheClassChild({name:'baby',grade:'class1',zzz:'bbbb'});
cc.alertA();
es6+的class创建与继承
class Student2{
constructor(props){
this.name=props.name||'';
}
hello(){
alert(this.name);
}
}
var s1=new Student2({name:'小张'});
s1.hello();
class PrimaryStudent2 extends Student2 {
constructor(props) {
super(props||{});
this.grade = props.grade||'';
}
myGrade() {
alert('I am at grade ' + this.grade);
}
}
var s2=new PrimaryStudent2({name:'小王',grade:'yi'});
s2.myGrade();