面向对象和面向过程的区别
面向过程
程序 = 算法+语法;
算法:强点的是步骤,一步接一步
面向过程编程的缺陷:
1、随着问题规模的增加,项目逐渐难以控制
2、复用性较差,只能复用函数
面向对象
程序 = 对象+对象+…+对象
对象->包含了相关功能的所有属性和方法
优点:优先考虑对象,最后再考虑过程
类和对象
分类:对每个对象进行抽象,描述出其属性和行为,进行归纳
抽象:对事物加以描述的过程
属性:名词->变量
行为:动词->函数
类:拥有相同属性和行为的对象的集合(它是一个模板,真实空间不存在,对象的抽象)
对象:根据类属性和行为创建的实例化(强调唯一性,真实存在)
ES5创建类
// 构造函数和普通函数的区别
// 1.习惯上构造函数首字母大写
// 2.构造函数不能自己写return(因为默认返回的是new出来的堆地址)
// 3.构造函数必须和new连用
// Array Date RegExp->自定义类
// JS虽然是面向对象的思想,但是没有类的语法,
// ES6之前,js的类都是通过函数模拟的
// 该函数称为构造函数,也称为类
// Student
// 属性:
// let name;
// let age;
// let gender;
// 行为:
// study
// eat
//this:
//1.与构造方法连用,代表new出来的对象
//2.与事件体连用,代表触发该事件的元素
//3.与普通普通函数(除了构造函数和事件体)连用,代表调用函数的对象
//4.与箭头函数连用,代表父元素的前缀
//--------------------------------
//注意事项:在成员函数中使用其他的成员属性,必须添加this前缀
function Student(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
this.study = function(){
console.log("我爱学习");
}
this.eat = function(){
console.log("其实我更爱吃");
}
this.showValue = function(){
console.log(this.name,this.age,this.gender);
this.study();
this.eat();
}
}
// let s1 = new Student("李佳琪",18,'M');//得到了一个new出来的对象
// console.log(s1.name,s1.age,s1.gender);
// s1.study();
// s1.eat();
// let s2 = new Student("药水哥",28,'M');//得到了一个new出来的对象
// console.log(s2.name,s2.age,s2.gender);
// s2.study();
// s2.eat();
//--------------------
let s1 = new Student("李佳琪",18,'M');
s1.showValue();
let s2 = new Student("药水哥",28,'M');
s2.showValue();
ES6
语法规则
// class 类名 {
// //构造函数,定义属性
// constructor(形参){
// this.属性 = 形参;
// }
// //行为,去掉function关键字
// eat(){
// }
// }
例子:
class Student{
constructor(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
}
study(){
console.log("初中生补课2小时800");
}
showValue(){
console.log(this.name,this.age,this.gender);
this.study();
}
}
let s = new Student("张乐",18,'M');
// console.log(s);
// s.study();
s.showValue();
类的组合
// 组合:一个类的属性是另一个类的对象
class Birthay{
constructor(y,m,d){
this.y = y;
this.m = m;
this.d = d;
}
showValue(){
console.log(this.y,this.m,this.d);
}
}
class Student{
constructor(name,age,gender,bir){
this.name = name;
this.age = age;
this.gender = gender;
this.bir = bir;
}
showValue(){
this.bir.showValue();
console.log(this.name,this.age,this.gender);
}
}
let bir = new Birthay(2023,9,12);
// bir.showValue();
let s = new Student("蔡徐坤",23,'M',bir);
// window.document.write
// s.bir.y
// console.log(s.bir.y);
s.showValue();