面向对象
面向过程
- 打开冰箱门
- 把大象装进去
- 关上冰箱门
面向对象
- 大象
- 冰箱
- 隐藏对象(把大象装进冰箱的手或人)
类与对象
类(class)是对象(object)的模板,定义了同一组对象共有的属性和方法
类
es5中的类
// es5中的类
function People(name,age){
this.name = name;
this.age = age;
People.count++
// this.showName = function(){ //写在这里,实例化的时候就会存在实例化的对象里
// console.log('my name is:' +this.name);
// }
}
People.count = 0
People.getCount = function(){
console.log('当前count:'+People.count);
}
// 写在这里,实例化的对象里调用方法,才执行
People.prototype.showName = function(){
console.log('my name is:' +this.name);
}
let p1 = new People('aa',1)
console.log(p1);
p1.showName()
People.getCount()
let p2 = new People('bb',2)
console.log(p2);
p2.showName()
People.getCount()
es5中的继承
// 组合继承
function Animal(name){
this.name = name;
}
Animal.prototype.showName = function(){
console.log('name is:'+this.name);
}
function Dog(name,color){
Animal.call(this,name) //父类有name,这里就传name
this.color = color
}
Dog.prototype = new Animal()
Dog.prototype.constuctor = Dog
let d1 = new Dog('aa','red')
console.log(d1);
d1.showName()
es6中的类与继承
class People {
constructor(name,age){
this.name = name;
this.age = age;
this._sex = -1;
}
get sex(){
if(this._sex === 1){
return 'male'
}else if(this._sex === 0){
return 'female'
}else{
return 'error'
}
}
set sex(val){
if(val === 0 || val === 1){
this._sex = val
}
}
showName(){
console.log(this.name);
}
static getCount(){ //静态方法
return 5
}
}
People.count = 9 //静态方法要定义在外面
console.log(People.count); //9
console.log(typeof People); //function
let p1 = new People('aa',11)
console.log(p1); //People {name: "aa", age: 11, _sex: -1}
p1.sex = 5;
console.log(p1.sex); //error
console.log(People.getCount()); //5
class Coder extends People{
constructor(name,age,company){
super(name,age) //传递给父类的属性
this.company = company;
}
showCompany(){
console.log(this.company);
}
}
let c1 = new Coder('cc',3,'tc')
console.log(c1); //Coder {name: "cc", age: 3, _sex: -1, company: "tc"}
c1.showName() //cc
c1.showCompany() //tc
c1.sex = 1;
console.log(c1.sex); //male