面向对象介绍
JavaScript的面向对象
JavaScript中没有类的概念(ES6之前),因此我们通常称为基于对象,而不是面向对象.
虽然JavaScript中的基于对象也可以实现类似于类的封装、继承、甚至是多态。但是和传统意义的面向对象还是稍微有一些差异(后面我们会讲解它是如何实现的)
ECMA中定义对象是这样: 无序属性的集合, 属性可以包含基本值, 对象或者函数.
也就是对象是一组没有顺序的值组成的集合而已.
对象的每个属性或者方法都有一个名字, 而名字对应一个值. 有没有觉得非常熟悉?
没错, 其实就是我们经常看到和使用的映射(或者有些语言称为字典, 通常会使用哈希表来实现).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>面向对象介绍</title>
</head>
<body>
<script type="text/javascript">
var student1 = {
name:"小明",
score:520,
}
printScore(student1);
var student2 = {
name:"小强",
score:550,
}
printScore(student2);
function printScore(student){
console.log("姓名:"+student.name+"\n成绩:"+student.score)
}
var tongJi = {
total:0,
boyTotal:0,
girlTotal:0,
printResult:function(){
console.log("本校人数:"+this.total+"\n男生:"+this.boyTotal+"\n女生:"+this.girlTotal);
}
}
var student3 = new Student("小红",530,"女");
student3.printScore();
var student4 = new Student("小黑",550,"男");
student4.printScore();
var student5 = new Student("小花",520,"女");
student5.printScore();
tongJi.printResult();
console.log("student3.printScore==student4.printScore:"+(student3.printScore==student4.printScore));
function Student(name,score,sex){
tongJi.total++;
this.name = name;
this.score = score;
this.sex = sex;
if(sex == "男"){
tongJi.boyTotal++;
}else if(sex=="女"){
tongJi.girlTotal++;
}
this.printScore=function(){
console.log("姓名:"+this.name+"\n成绩:"+this.score)
}
}
</script>
</body>
</html>