es5与es6中面向对象的实现

在es5中实现面向对象 即通过构造函数和远行对象来实现

			/*es5 之前面向对象==============*/
			//定义对象  通过构造函数来实现类
			function Person(name,age){
				this.name = name;
				this.age = age;
			}
			//添加方法  通过原型来添加方法
			Person.prototype.show = function(){
				console.log(this.name+" -- "+this.age);
			}
			
			//创建实例
			var p = new Person('jack',18);
			p.show();
			
			//类继承
			function Student(name,age,job){
				Person.call(this,name,age);
				this.job = job;
			}
			//设置student的原型 指向Person,从而能访问Student中的方法
			Student.prototype = new Person();
			//需要重新设定Student的构造器
			Student.prototype.constructor = Student;
			Student.prototype.showJob = function(){
				console.log(this.job);
			}
			var student = new Student('rose',22,'学生');
			student.show();
			student.showJob();

在es6之后 有了class 关键字之后,不需要再通过构造函数来实现类 实现如下

			/* es6之后 实现面向对象 ============*/
			class Animal{
				constructor(name,age) {
					this.name = name;
					this.age = age;
				}
				show(){
					console.log(this.name + "--" + this.age);
				}
				jump(){
					console.log('jump is run. ');
				}
			}
			
			var animal = new Animal('dog',12);
			animal.show();
			animal.jump();
			
			/*实现继承*/
			class Cat extends Animal{
				constructor(name,age,type){
					super(name,age);//通过super关键字 来访问父类的构造函数,必须在this之前调用
					this.type = type;
				}
				showType(){
					console.log("type: " + this.type);
				}
			}
			
			var cat = new Cat('cat',3,'英短');
			cat.show();
			cat.jump();
			cat.showType();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值