在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();