JavaScipt高级笔记01 面向对象编程

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();
  • 注意:
    1. 通过class关键字创建类,类名首字母可以大写
    2. 类里面有个cunstructor函数,可以接受传递过来的参数,同时返回实例对象
    3. constructor函数,只要new生成实例时,就会自动调用这个函数,如果我们不写这个函数,类也会自动生成这个函数
    4. 生成实例new不能省略
    5. 创建类,类名后面不要加括号,生成实例,类名后面加括号,构造函数不需要加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,谁调用指向谁
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值