ES6 Class 类(一)
Class 类
OOP 面向对象的编程 (Object Oriented Programming)
OOD 面向对象的设计
OOA面向对象的分析
一. class类和instance(实例)的关系
实例(instance)是一个class变成一个实际的对象
例子:ES6以前,用原型的方式实现类 function Car(color,brand,power){ this.color = color; this.brand = brand; this.power = power; } let car1 = new Car('红色','大众',100); // function定义的类的缺陷 let car4 = new Car('绿色','甲壳虫',110); // undefined 函数没有返回值,返回undefined,函数this赋值成为window的属性 console.log(car4);//undefined console.log(window);
二. class的概念
class 是关键字,是es6提供给我们在js中写构造方法的语法糖;
class 也是一种声明变量的方法
生命周期、变量不重复、变量不提升、不挂载到window等等方面和let的特性一样
class 声明变量类型是function
例子: class Car{ // 声明成员(实例)变量,不是必须写的 // 成员变量,不用写let/const写了也会报错 color='黑色'; weight=1500; type; // 构造方法 constructor constructor(color){ this.price= 100000;//给固定值,成员变量 this.color = color; } // 在原型上的方法,可以直接写在class Car上 drive(){}; } let car = new Car('白色'); // 例子2: class A{} //js语言的分析器会自动不上一个空白的constructor // class A{constructor(){}}
三. 关于Class类的私有的成员(#)
例子: class Person{ #name = '';//私有属性 #age = 0; constructor(name,age){ this.#name = name; this.#age = age; } setName(name){ if(typeof(name) !== 'string'){ throw new Error('名字必须是字符串'); }else if(!(name.length >= 2 && name.length <= 10)){ throw new Error('名字的长度必须在2-10个字符之间'); } this.#name = name; } toString(){ return `我的名字是${this.#name},今年${this.#age}岁` } } let p = new Person('zhangsan',20); // console.log(p.#name);//报错,不能设置私有属性 console.log(p.name);//和#name不是同一个属性,可以访问 p.setName('张三丰');//更改私有属性名字和名字限制 console.log(p.toString());//和#name不是同一个属性,可以访问
四. 类的setter/getter 方法 (写/读)
例子: class Person{ #name; #age = 0; get name(){ console.log('调用get name方法'); return this.#name; } set name(s){ console.log('调用set name方法',s); this.#name = s; } get age(){ console.log('get age'); return this.#age; } set age(age){ console.log('set age',age); if(age < 0 || age > 140){ throw new Error('无效的age值'); } this.#age = age; } } let p = new Person(); // set 写的过程,从p实例上的name属性赋值 p.name = 'zhangsan'; // get 读的过程,从p实例读取name属性 console.log(p.name); // 先get 再set 再get console.log(++p.age)
五.class中的错误
例子: class A{ y; get y (){//错误,永远也不会调用 console.log('get y'); return this.y; } // 会造成死循环 get x(){ return this.x; } set x(x){ this.x = x; } } let a = new A(); a.y();//错误
浙公网安备 33010602011771号