1.面向对象
- 面向过程编程POP,按照分析的步骤解决问题
- 面向对象编程OOP,以对象为功能中心
- 特性:封装性,继承性,多态性
1.1类
- ES6中新增加了类的概念,可以使用关键字class声明一个类
- 创建类:
//步骤1 使用class关键字
class name {
// class body
}
//步骤2使用定义的类创建实例 注意new关键字
var xx = new name();
- 添加属性和方法
- 共有属性放在constructor里面,所有的函数都不需要function
class star{
//类的共有属性放到constructor里面
constructor(uname,age){
this.uname = uname;
this.age = age;
}
sing(){
console.log('lalala');
}
}
var yy = new star('yy',30);
console.log(wl);
yy.dance();
- 注意:
- 通过class关键字创建类,类名首字母可以大写
- 类里面有个cunstructor函数,可以接受传递过来的参数,同时返回实例对象
- constructor函数,只要new生成实例时,就会自动调用这个函数,如果我们不写这个函数,类也会自动生成这个函数
- 生成实例new不能省略
- 创建类,类名后面不要加括号,生成实例,类名后面加括号,构造函数不需要加function
1.2类的继承
- extends,继承父类的方法
// 父类
class Father{
}
// 子类继承父类
class Son extends Father {
}
-== super==,调用父类中的函数
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x + this.y);
}
}
class Son extends Father {
constructor(x, y) {
super(x, y); //使用super调用了父类中的构造函数
}
}
var son = new Son(1, 2);
son.sum(); //结果为3
- super调用普通函数
class Father{
say(){
return '我是爸爸'
}
}
class Son extends Father{
say(){
console.log(super.say() + '的儿子');
//super.say()就是调用父类中的普通函数say()
}
}
var son = new Son();
son.say();
1.3补充说明
- 在ES6中没有变量提升,必须先定义类,再实例化
- 类里面共有的属性和方法一定要加this使用
- constructor的this指向创建的实例对象
- 方法里面的this,谁调用指向谁