一.面向对象与面向过程
1.面向过程的编程思想
面向过程的编程思想:程序 = 语法 + 算法
算法:强调步骤,一步接一步
缺陷:
1)随着问题规模的增加,代码逐渐难以控制
2)复用性较差(只有函数)
2.面向对象的编程思想
程序 = 对象1 + 对象2 + ... + 对象N
思想:
1)优先强调该问题出现的对象
2)最后才去考虑过程
对象的理解包含了相关自身操作的所有属性和方法
对象:万物皆为对象,可以是有形的,也可以是无形的(比如某些规则)
二.类与对象
抽象:对事物加以描述的过程,描述出名词和动词
类:拥有相同属性和行为的对象集合,它是一个模板
对象:类的实例化,强调真实且唯一
三.ES5创建类
1.this的作用
1)与事件体连用,代表触发该事件的元素;
2)与普通方法连用,代表调用该方法的对象;
3)与构造方法连用,代表new开辟出来的对象;(所以构造函数没有进行实
例化的时候,this是不存在的)
4)在箭头函数中,代表箭头函数父元素的前缀;
2.普通方法和构造方法的区别
1)构造方法不能有return,因为它自动返回new开辟出来对象的地址
2)构造方法必须和new关键字连用,功能为创建对象
3)习惯上构造方法首字母大写
3.通过构造函数模拟类
ES5之前没有类这个语法,但是却需要用到类的思想:通过函数模拟类--->该函数是构造函数:构造对象的函数
类的定义:
function Student(name,id,score){
this.name = name;
this.id = id;
this.score = score;
this.eat = function(){
console.log("eat");
}
this.study = function(){
console.log("study");
}
this.showValue = function(){------------ES5版本,方法要带this和function
console.log(this.name,this.id,this.score);
this.eat();--------------------------------------在一个成员方法中使用其他的成员,需要添加前缀this
this.study();
}
}
对象的定义:
let s1 = new Student("老王",1,100);
console.log(s1.name,s1.id,s1.score);--------------对象的使用
s1.eat();
s1.study();
s1.showValue();
let s2 = new Student("小敏",2,1000);
console.log(s2.name,s2.id,s2.score);
s2.eat();
s2.study();
s2.showValue();
四.ES6创建类
class 类{
构造方法:类内的特殊方法,只用来构造对象,new类名调用的就是该方法
constructor(){
}
普通方法
}
class Student{
创建属性(需要写在constructor里面)
constructor(id,name,score){
this.id = id;
this.name = name;
this.score = score;
}
eat(){--------------------------Es6版本,方法不带this和function
console.log("eat");
}
study(){
console.log("study");
}
}
let s1 = new Student(111,"老王",9999);------------创建对象
console.log(s1.id,s1.name,s1.score);
s1.eat();
s1.study();-----------------------调用方法