什么是对象?
什么是面对对象?
面向对象与面向过程:
面向过程的体现
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 面向过程创建对象
// 1.定义学生信息
var stu1 = {
name:'张三',
age:18,
sex:"男"
}
var stu2 = {
name:'李四',
age:20,
sex:"女"
}
// 2.定义方法
// 处理学生的年龄
function printAge1(){
console.log(stu1.name+" "+stu1.age);
}
// 处理学生的年龄
function printAge2(){
console.log(stu2.name+" "+stu2.age);
}
// 3.调用
printAge1()
printAge2()
</script>
</body>
</html>
面向对象的基本体现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 1.创建学生类
function Student(name, score) {
// 将传进来的值赋值给Student类中的属性
this.name = name
this.score = score
}
// 2.在原型上添加学生的方法
// Student.prototype 学生类的原型
Student.prototype.printScore = function () {
console.log(this.name + ' ' + this.score);
}
Student.prototype.printName = function () {
console.log(this.name);
}
// 3.创建学生的对象 (创建实例)
// 我们在使用new的时候 new的是Student类的构造方法
var s1 = new Student('张三',80)
var s2 = new Student('李四',90)
// 4.通过学生的对象调用方法
s1.printScore()
s2.printScore()
console.log(s1);
// 在原型上包含我们自己定义的方法 printScore
// 还自带一个构造方法 constructor
</script>
</body>
</html>