高级会员
- 积分
- 585
- 金钱
- 585
- 注册时间
- 2020-5-25
- 在线时间
- 42 小时
|
概念 -类
类即模板
对象-实例 示例 //类-模板class Person{ constructor(name,age){ this.name = name; this.age = age; } eat(){ alert(`${this.name} eat something`); } speak(){ alert(`My name is ${this.name}, age ${this.age}`); }}//对象-实例let zhang = new Person('zhang',20);zhang.eat();zhang.speak();let wang = new Person('wang',21);wang.eat();wang.speak();三要素
继承,子类继承父类 封装,数据的权限和保密 多态,同一接口不同实现 继承
示例 //类-模板class People{ constructor(name,age){ this.name = name; this.age = age; } eat(){ alert(`${this.name} eat something`); } speak(){ alert(`My name is ${this.name}, age ${this.age}`); }}class Student extends People{ constructor(name,age,number){ super(name,age); this.number = number; } study(){ alert(`${this.name} study`); }}let xiaoming = new Student('xiaoming',10,'A1');xiaoming.study();alert(xiaoming.number);xiaoming.eat();let xiaohong = new Student('xiaohong',11,'A2');xiaohong.study();xiaohong.speak();封装 - public 完全开放
- protected 对子类开放
- private 对自己开放
- (ES6不支持,TypeScript演示)
说明 - 减少耦合,不该外露的不外露
- 利于数据、接口的权限管理
- ES6目前不支持,一般认为_开头的属性是private
示例 //类-模板class People{ name; age; protected weight; constructor(name,age){ this.name = name; this.age = age; this.weight = 120; } eat(){ alert(`${this.name} eat something`); } speak(){ alert(`My name is ${this.name}, age ${this.age}`); }}class Student extends People{ number; private girlfriend; constructor(name,age,number){ super(name,age); this.number = number; this.girlfriend = 'xiaoli'; } study(){ alert(`${this.name} study`); } getWeight(){ alert(`weight ${this.weight}`); }}let xiaoming = new Student('xiaoming',10,'A1');xiaoming.getWeight();//alert(xiaoming.girlfriend);多态 - 同一个接口,不同表现
- JS应用极少
- 需要结合java等语言的接口、重写、重载等功能
说明 - 保持子类的开放性和灵活性
- 面向接口编程
- (JS应用极少)
class People{ constructor(name){ this.name = name; } saySomething(){ }}class A extends People{ constructor(name){ super(name); } saySomething(){ alert('I am A'); }}class B extends People{ constructor(name){ super(name); } saySomething(){ alert('I am B'); }}let a = new A('a');a.saySomething();let b = new B('b');b.saySomething();应用举例
index.js class jQuery { constructor(seletor) { let slice = Array.prototype.slice; let dom = slice.call(document.querySelectorAll(seletor)); let len = dom ? dom.length : 0; for (let i = 0; i < len; i++) { this = dom; } this.length = len; this.seletor = seletor || ''; } append(node) { //…… } addClass(name) { //…… } html(data) { //…… } //其他}window.$ = function (selector) { return new jQuery(selector);}//测试代码var $p = $('p');console.log($p);console.log($p.addClass);index.html <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <p>测试-1</p> <p>测试-2</p> <p>测试-3</p> <p>测试-4</p> <p>测试-5</p> <script type="text/javascript"> // var $p = $('p'); // console.log($p); // console.log($p.addClass); </script></body></html>- 程序执行:顺序、判断、循环 - 结构化
- 面向对象:数据结构化
- 对于计算机,结构化的才是最简单的
- 编程应该 简单&抽象
|
|