Day12-面向对象编程
一 回顾
变量,数组,对象都是容器,都可以用来存储数据
let n = 10
let arr = [3,5,7]
let stu = {name:"张恒",age:18,sex:"女"}
二 面向对象思想
面向过程:将开发的步骤按照顺序一步一步往下执行,直到程序结束
面向对象:将项目中要涉及到对象抽取出来,每个对象负责自己那一部分数据,对象之间相互调用完成业务
类:一类事务的统称
对象:某一个具体的事务
对象的属性:对象的特性(年龄,身高,肤色,性别)
对象的方法:对象的行为(学习,睡觉,吃饭,跑步,打架)
三 对象的创建
先造模具:模具就是类
function Student(name,sex,age){
this.name = name
this.sex =sex
this.age =age
}
然后把类作为模具来创建对象容器
//使用类创建对象
let stu1 = new Student()
stu1.name = "赵日天"
stu1.sex = "男"
stu1.age = 20
console.log(stu1);
//使用类创建对象
let stu2 = new Student("李杀神","男",21)
console.log(stu2);
//使用类创建对象
let stu3 = new Student("王诛魔","女",22)
console.log(stu3);
let stu4 = new Student("刘斩仙","男",23)
练习:创建对象把下面5件商品的信息存储起来,并打印输出
四 对象中的方法
五 继承
父类
function Student(name,sex,age){
this.name = name
this.sex =sex
this.age =age
// 类方法
this.eat = function(){
console.log(this.name+"吃饭");
}
}
子类
/**
* 继承
* A类(子类)继承Student类(父类)
* 子类继承父类,子类拥有父类所有的属性和方法
*/
function A(){
Student.call(this)
}
子类对象
//创建对象
let a = new A()
a.name = "赵昊"
a.sex = "男"
a.age = 200
console.log(a);
a.eat()
六 new
new的作用:调用构造函数实例化对象
new的过程中干了哪些事情:
创建一个空对象,并在内存中开辟相应的空间,将它的引用赋给 this
通过 this 将属性和方法添加至这个对象
最后返回 this 指向的新对象