1.为什么:重用、组织代码
2.怎么用
3.应用范围
4.实例
5.面试
一、面向对象的概念
在面向对象程序开发思想中,每—个对象都是功能中心。 面向对象编程具有灵活、代码可复用、容易维护和开发的优点,更适合多人合作的大型软件项目。
1.1面向对象的特性:
- 封装性:把相近的东西、屏蔽对象的细节(降低成本、保密)
- 继承性:从已有的类继承一个新类
- 多态性:子类也是父类
1.2 类和对象:
1.2.1 类 对象
let oDate = new Date();
对象 类
- 类(class):本身没有功能、用来构造实例 工厂
- 对象(instance):具备功能
1.2.2 成员
- 成员变量、成员属性、成员函数、成员方法
1.2.3 实例化 new
二、类
两种写法。ES5的写法了解就行,已经是过去式了。
类的组成
- 成员变量 5 / 6
- 成员函数 5 / 6
- constructor 6
- 访问器 6
类的写法
1.ES5
ES5中没有专门的类的写法,函数就是类,所有也叫做构造函数。
构造函数其实就是普通函数,只不过是一个叫法。
//构造函数
function Person(){
this.a=12;
this.name='blue';
this.show=function(){
alert('aaa');
}
}
//实例化对象
let p=new Person();
console.log(p);
问题1:函数和类混淆了
问题2:new到底是什么
new会改变this,变成一个新创建的实例
this不是由定义决定的,是由调用决定的
问题3:直接添加方法不好的?
this指向问题
this | 普通函数 | 箭头函数 |
由谁决定 | 调用 | 定义 |
直接执行 | window | 环境 |
事件 | 事件所属对象 | 环境 |
new | 新实例 | 报错 |
成员 | 所属实例 | 环境 |
prototype、原型
作用:节省资源(只存一份)、动态调整类的成员-常见于系统对象
用处:同一个类的所有实例,共享prototype上的成员
原型原理:
首先,寻找实例自己。
继续,类的prototype。
再继续,父类的prototype。
再继续2,父类的prototype2。
........
undefined
function Person(name,age){
this.name =name;
this.age=age;
}
Person.prototype.show=function(){
console.log(`姓名:${this.name},年龄:${this.age}`);
}
let p1=new Person('blue',18);
let p2=new Person('zhangsan',25);
let p3=new Person('lisi',99);
console.log(p1.show);
consloe.log(p2.show);
consloe.log(p1.show===p2.show); //true
ES6写法
class Person{
constructor(name,age){
this.name =name;
this.age=age;
}
show(){
console.log(`姓名:${this.name},年龄:${this.age}`)
}
}
let p=new Person('blue',18);
console.log(p);
constructor就相当于ES5中的function。方法也不需要往原型里面写了,ES6这样写的方法就是加到原型里了。
访问器
- 不用直接访问变量本身,通过访问器来受控访问类的变量
- 看着像变量,背后是两个变量 getter、setter
实例:简易用户封装类
class User{
_username='';
_password='';
constructor(username,password){
this.username=username;
this.password=password;
}
login(){
if(this.username=='blue' && this.password='123123'){
return true;
}else{
return false;
}
}
get username(){
return this._username;
}
set username(val){
if(typeof val!='string'){
throw new TypeError('username必须是字符串');
}
if(!/^\w{6,32}$/.test(val)){
throw new ValueError('username格式不对');
}
this._username=val;
}
}
let user1=new User('blue','12345');
if(user1.login()){
alert('登录成功');
}else{
alert('登录失败');
}
类的继承
super :访问父类/基类/超类
super(); 访问父类的constructor
super.xxx; 访问父类的成员
//父类
class Base{
a=0;
b=0;
constructor(a,b){
this.a=a;
this.b=b;
}
sum(){
return this.a+this.b;
}
}
//继承父类的子类
class Dervied extends Base{
c=0;
constructor(a,b,c){
super(a,b); //继承父类的属性
this.c=c;
}
sum(){
let res=super.sum();
return res+this.c;
}
}
let obj=new Derived(12,5,33);