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) { // 对于new构造函数的封装,其优点:一是不需要new来调用,二是参数灵活
    return new Student(props || {}) // 通过new创建构造函数,并传入参数/属性
}

var niming = createStudent(); 
niming.hello();

var xiaoming = createStudent({
  name:'小明',
  grade:2
});
xiaoming.hello();


//继承
function inherits(Child, Parent) { // 继承的封装方法 inherits(子类, 父类) 
    var F = function () {}; // 定义空方法F
    F.prototype = Parent.prototype; //F原型指向父类原型
    Child.prototype = new F(); // 子类原型指向 new F() 方法
    Child.prototype.constructor = Child; // 修正子类原型上的构造函数为子类本身函数
}

function PrimaryStudent(props) { //定义子类 构造函数
    Student.call(this, props); // 修正this指向
    this.age = props.age || 8; //新增子类属性
}

inherits(PrimaryStudent, Student);//调用继承封装方法实现继承

PrimaryStudent.prototype.getAge = function(){ //对子类添加方法
  console.log(this.name +'同学,你今年'+ this.age +'岁');
}


//使用继承后的
function createPrimaryStudent(props) { // 对于new构造函数的封装,其优点:一是不需要再new来调用,二是参数灵活
    return new PrimaryStudent(props || {}) // 通过new创建构造函数,并传入参数/属性
}

var xiaohong = createPrimaryStudent({
  name:'小红',
  grade:3,
  age:10
});
xiaohong.hello();
xiaohong.getAge();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值