ES5面向对象
function Student(props){
this.name = props.name || '匿名';
this.grade = props.grade || 1;
}
Student.prototype.hello = function(){
console.log('你好,'+ this.name +'同学,你在'+ this.grade+'年级');
}
function createStudent(props) {
return new Student(props || {})
}
var niming = createStudent();
niming.hello();
var xiaoming = createStudent({
name:'小明',
grade:2
});
xiaoming.hello();
function inherits(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
function PrimaryStudent(props) {
Student.call(this, props);
this.age = props.age || 8;
}
inherits(PrimaryStudent, Student);
PrimaryStudent.prototype.getAge = function(){
console.log(this.name +'同学,你今年'+ this.age +'岁');
}
function createPrimaryStudent(props) {
return new PrimaryStudent(props || {})
}
var xiaohong = createPrimaryStudent({
name:'小红',
grade:3,
age:10
});
xiaohong.hello();
xiaohong.getAge();