-JS面向对象编程 -- 三大特征
- 封装
- 继承
- 多态
-重载和覆盖
-综合案例
1. 概念
1.1 抽象
把一类事物共有的属性和行为抽取出来,
形成一个物理模型(模板).
这种研究问题的方法称为抽象.
1.2 封装
1) 介绍
封装就是把抽象出来的属性和对属性的操作封装在一起,
属性被保护在内部,
外部, 只有通过被授权的操作(函数), 才能操作属性.
2) 访问权限
① 公有: 对外公开
② 私有: 只有类里面才可访问
3) 举例
function Employee() { this.name = "张三"; // 公有属性 var salary = 3000; // 私有属性 this.getSalary = function() { // 公有方法(特权方法) return this.salary; } this.display = function() { // 公有方法 调用 私有方法 return show(this); } function show() { // 私有方法(内部方法),可访问私有属性 return name + "---" + salary; } } var emp = new Employee(); console.info( emp.name ); console.info( emp.salary ); console.info( emp.getSalary ); console.info( emp.display() ); /* 张三 undefined function() ---3000 */
4) 注
使用 prototype 定义的方法, 不能访问私有属性/方法.
1.3 继承
1) 继承的必要性
①更符合人的思维习惯
②代码复用
2) 继承的实现
通过对象冒充的方式, 可实现多继承
Object是 所有类 的基类
3) 示例
// 基类 function Person(name, age) { this.name = name; this.age = age; this.show = function() { return this.name + "---" + this.age; } } // 扩展类 function Student(name, age) { // 将所有的属性和方法 赋值给 属性person this.person = Person; // 初始化, JS动态语言,如不初始化则不会分配内存 this.person(name, age); } var stu = new Student("张三", 24); console.info( stu.show() ); // 张三---24
1.4 多态
多态是指一个引用在不同情况下的多种状态.
Java中是通过指向父类的引用,来调用不同子类中实现的方法.
JS中, 变量的类型由JS引擎动态决定.
如:
var obj = new Cat();
obj.eat();
obj = new Dog();
obj.eat();
2. 重载(overloading) 和 覆盖(overriding)
2.1 重载
同一种功能的不同实现, 通过参数列表区分.
JS不支持重载, 因为JS参数(类型和个数)可变
2.2 覆盖
原理: 重名的方法后者覆盖前者.
// 基类 function Person(name, age) { this.name = name; this.age = age; this.show = function() { return this.name + "---" + this.age; } } // 扩展类 function Student(name, age) { // 将所有的属性和方法 赋值给 属性person this.person = Person; // 初始化, JS动态语言,如不初始化则不会分配内存 this.person(name, age); // 覆盖, 比Person中的show后出现. this.show = function() { return this.name + "+++" + this.age; } }
3. 综合案例
//------------- // 主人 function Master(name) { this.name = name; this.feed = function(animal, food){ return this.name + "给" + animal.name + "喂" + food.name; } } //------------- // 动物 function Animal(name) { this.name = name; this.eat = function(food) { return this.name + "吃" + food.name; } } // 狗 function Dog(name) { this.animal = Animal; this.animal(name); } // 猫 function Cat(name) { this.animal = Animal; this.animal(name); } //------------- // 食物 function Food(name) { this.name = name; } // 骨头 function Bone(name) { this.food = Food; this.food(name); } // 鱼 function Fish(name) { this.food = Food; this.food(name); } //------------------------------------ var fishFood = new Fish("鲫鱼"); // console.info( fishFood.name ); var catAnimal = new Cat("小白猫"); // console.info( catAnimal.name ); var master = new Master("张三"); // console.info( master.name ); console.info( master.feed(catAnimal, fishFood) ); // 张三给小白猫喂鲫鱼 // --------------- var boneFood = new Bone("大骨头"); var dogAnimal = new Dog("大黑狗"); console.info( master.feed(dogAnimal, boneFood) ); // 张三给大黑狗喂大骨头