什么是JS面向对象编程(OOP)?
用对象的思想去写代码,就是面向对象编程。
上面这张图就是一个对象,紫色部分就是车的属性,黄色部分就是修改车的方法;
把他们集合到一个构造函数内,就是这样的
function Car(name, color, structure){
this.name = name;
this.color = color;
this.structure = structure;
this.setName = function (name){
this.name = name
}
this.getName = function (){
return this.name;
}
}
let car1 = new Car('保时捷', '红色', 'SUV');
console.log(car1.getName()) // 输出 ===> 保时捷
初代造车对象呢,不具备修改颜色,也就是我造的都是红色,你买不到别的颜色,车企肯定不想这样,那你制造商就得想办法解决一下,所以我决定升级一下继续研发,来个车间给我改颜色
Car.prototype.setColor = function (color){
this.color = color
};
Car.prototype.getColor = function (){
return this.color;
};
car1.setColor('绿色')
console.log(car1.getColor()) // 输出 ===> 绿色
现在呢问题又来了,说你生产的都是suv,能不能给我提供一下 轿车的车架,可是我厂房不够啊,这可咋整扩建吧!于是我们开始扩建了我的车架厂房,哈哈 身为甲方我们是真孙子啊
// 车对象升级图纸
function Carupgrade(){
this.setStructure = function (structure){
this.structure = structure
}
this.getStructure = function (structure){
return this.structure;
}
}
// 继承原车的基础
Carupgrade.prototype = new Car('保时捷', '红色', 'SUV');
// 创建厂房2
let car2 = new Carupgrade();
// 修改车架车间
car2.setStructure('轿车')
// 修改完成看看你这车啥样的
console.log(car2.getName(), car2.getColor(), car2.getStructure()) // 输出 ===> 保时捷 红色 轿车
有了这些厂房基础,你不就想造啥车造啥车,媳妇再也不担心会坐在自行车上哭了。(捂脸偷笑,啪啪啪,醒一醒)*
面向对象编程特点
通过上面介绍咱们来总结一下面向对象编程特点吧!
- 封装:针对对象属性,以及修改属性的方法进行封装;
- 继承:你可以在创建新对象的时候继承来自上一个对象的所有属性和方法(Carupgrade.prototype = new Car(‘保时捷’, ‘红色’, ‘SUV’););
- 多态:具体表现为方法重载和方法重写( prototype )
在JS的世界里一切都是对象,如果你看过JS什么是对象,那么你会发现数组、字符串、对象、undefined、function、他们都是对象的集合体,或者是对象的一种表现形式,但是你没有总结这些问题的重复性,和可利用性,代码冗余就变成了你项目中的常见特点,现在框架都是采用构造函数的方式写的,封装,继承,你独立写的部分就是多态,这么说你是不是对面向对象有清晰的认识了,
如果每一个造车的部门都要新建所有的车间,那么你就需要更多的土地建厂,但是你会发现重复的车间太多了,他们产能过剩已经超出你的需求,这就是我们为啥要利用构造函数,来写一个面向对象编程了。
ES6 构造函数语法糖 class 类
class 就是省级版构造函数。class 的继承 extends 就是构造函数的原型链的继承。
基本上,ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。上面的代码用 ES6 的class改写,就是下面这样。(这句话我引用阮一峰大神的文章原话,代码时我自己的以上面es5写法一对一替换啊)
class Car {
constructor(name, color, structure) {
this.name = name;
this.color = color;
this.structure = structure;
}
setName (name){
this.name = name
}
getName (){
return this.name;
}
}
let car1 = new Car('保时捷', '红色', 'SUV');
console.log(car1.getName()) // 输出 ===> 保时捷
然后我们使用prototype为类方法新增方法,跟es5是一样的
Car.prototype.setColor = function (color){
this.color = color
};
Car.prototype.getColor = function (){
return this.color;
};
car1.setColor('绿色')
console.log(car1.getColor()) // 输出 ===> 绿色
最后咱们看看继承吧
// es6 就不用prototype 或其他方法继承了 extends就可以直接继承
class Carupgrade extends Car {
constructor(name, color, structure) {
super(name, color, structure); // 调用父类的constructor(name, color, structure)
// super 这个是必须的他继承父类的属性方法啊,你要啥弄啥就行
}
setStructure (structure){
this.structure = structure
}
getStructure (structure){
return this.structure;
}
}
let car2 = new Carupgradenew('保时捷', '红色', 'SUV');
car2.setStructure('轿车')
console.log(car2.getName(), car2.getColor(), car2.getStructure())
所有的方法都继承了,而且简洁了是吧