1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| 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();
|