通过 class 关键字,可以定义类
类的数据类型就是函数,类本身就指向构造函数。使用时,直接对类使用 new 命令,跟构造函数的用法完全一致。
类的所有方法都定义在类的 prototype 属性上。
在类的实例上面调用方法,其实就是调用原型上的方法。
在类的内部所有定义的方法,都是不可枚举的(non-enumberable),与ES5行为不一致
-
constructor 方法
constructor 方法是类的默认方法,通过 new 命令生成对象实例时,自动调用该方法。
一个类必须有 constructor 方法,如果没有显示定义,一个空的 constructor 方法会被默认添加。
constructor 方法默认返回实例对象(即this),但也可以指定返回另一个对象。
类 必须用 new 调用。
-
类的实例
实例的属性除非显示定义在其本身(即定义在 this 对象上),否则都是定义在原型上(即定义在 class 上)。
类的所有实例共享一个原型对象。这就说明可以通过 __proto__属性在原型上添加方法。但使用 __proto__属性改写原型,必须相当谨慎,不推荐使用,因为会改变"类"的原始定义,影响到所有实例。
class Point{
constructor(x,y){
this.x = x;
this.y = y;
}
toString(){
return '('+this.x +', '+this.y +')';
}
}
var point = new Point(2,3);
var a = point.toString();
point.hasOwnProperty('x') //true
point.hasOwnProperty('y') //true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') //true
/* x,y是实例对象point自身的属性(显示定义在this 对象上),
toString 是定义在原型对象的属性(定义在 class 上) **/
/*类的所有实例共享一个原型对象**/
var point = new Point(2,3);
var point2 = new Point(1,4);
point.__proto__ == point2.__proto__ //true
/*使用 __proto__ 属性在原型上添加方法,会影响到所有实例**/
point.__proto__.printName = function(){return "proto"};
point.printName(); //"proto"
point2.printName(); //"proto"
/*生产环境中,推荐使用 Object.getPrototypeOf() 方法来获取实例对象的原型,再为原型添加方法/属性。避免对环境产生依赖**/
var pointProto = Object.getPrototypeOf(point);
pointProto.printName = function(){return "Object Proto"};
point.printName(); //"Object Proto"
point2.printName(); //"Object Proto"
__proto__
并不是语言本身的特性,这是各大厂商具体实现时添加的私有属性,虽然目前很多现代浏览器的 JS 引擎中都提供了这个私有属性,但依旧不建议在生产中使用该属性,避免对环境产生依赖。生产环境中,我们可以使用Object.getPrototypeOf
方法来获取实例对象的原型,然后再来为原型添加方法/属性
-
取值函数(getter)和存值函数(setter)
在类的内部可以使用 get 和 set 关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。
存值函数和取值函数是设置在属性的 Descriptor 对象上的。
class Myclass{
constructor(element){
this.element = element;
}
get prop(){
return this.element;
}
set prop(val){
this.element = val;
}
}
let decriptor = Object.getOwnPropertyDescriptor(Myclass.prototype,"prop");
let inst = new Myclass();
inst.prop = 123;
inst.prop //123
"get" in decriptor //true
"set" in decriptor // true
-
属性表达式与Class 表达式
类的属性名,可以采用表达式。
类也可以使用表达式的形式定义。
let methodName = 'getClassName';
// Class 表达式
const MyClass = class Me{
//属性表达式
[methodName](){
return Me.name;
}
}
let inst = new MyClass();
/*在外部只能用 MyClass 这个类引用,在类的内部只能使用 Me 这个类,指代当前类.
若类的内部没用到类名相关属性的话,可以省略 类名。constMyClass=class{/* ... */};
*/
inst.getClassName() // "Me"
-
注意点
(1)严格模式,类和模块的内部,默认为严格模式
(2)类不存在变量提升
(3)name 属性总是返回紧跟在 class 关键字后面的类名
(4)this 指向,类的方法内部如果含有 this,默认指向类的实例。但是如果将包含 this 的方法单独使用,this 会指向该方法运行时所在的环境(由于 class 内部是严格模式,this 实际指向 undefined),从而会导致找不到此方法报错。
解决办法1:在构造函数中绑定 this
解决办法2:使用箭头函数
解决办法3:使用Proxy,获取方法的时候,自动绑定 this
class Logger{
/*解决办法1,在构造函数中绑定 this*/
// constructor(){
// this.printName = this.printName.bind(this);
// }
// printName(name='there'){
// this.print(`Hello ${name}`);
// }
/*解决办法2 使用箭头函数,箭头函数内部的 this 总是执行定义时所在的对象。*/
printName = (name='there')=>this.print(`Hello ${name}`);
print(text){
console.log(text);
}
}
const logger = new Logger();
const {printName} = logger;
printName();// ncaught TypeError: Cannot read property 'print' of undefined
/*解决办法1,在构造函数中绑定 this*/
/*constructor(){
this.printName = this.printName.bind(this);
}
*/
/*解决办法2使用箭头函数,箭头函数内部的 this 总是执行定义时所在的对象。*/
// printName = (name='there')=>this.print(`Hello ${name}`);
/*解决办法3 使用Proxy,获取方法的时候,自动绑定 this*/
-
静态方法、实例属性、静态属性
静态方法:
类相当于实例的原型,所有在类中定义的方法,都会被实例继承。但若在属性或方法前加上 static 关键字,就表示该方法不会被实例继承,而是直接通过类调用,称为静态方法。
(1)静态方法直接通过类来调用。若在实例上调用静态方法,会抛出一个错误,表示不存在该方法
(2)若静态方法中包含 this 关键字,this 指向的时类,而不是实例
(3)静态方法可以与非静态方法重名。
(4)父类的静态方法可以被子类继承
(5)静态方法可以用 super 关键字调用父级的静态方法
实例属性:
(1)可以定义在 constructor()构造函数中的 this 对象上
(2)也可以定义在类的最顶层
静态属性:
静态属性指的是 Class 本身的属性,即 Class.propName,而不是定义在实例对象(this)上的属性。
注:静态属性有两种写法
(1)老写法:
(2)新写法:
class Foo {
//实例属性也可以定义在类的顶层
fooName = "132";
constructor(){
//实例属性可以定义在构造函数中的 this 对象中
this._count = 0;
}
//静态方法直接通过类来调用。若在实例上调用静态方法,会抛出一个错误,表示不存在该方法
static classMethod() {
return 'hello';
}
/*若静态方法中包含 this 关键字,this 指向的时类,而不是实例*/
static bar(){
console.log(this.fooName);
}
/*静态方法(属性)可以与非静态方法(属性)重名。*/
static fooName = "hanbaobao";
}
Foo.classMethod() // 'hello'
var foo = new Foo();
//foo.classMethod()
// TypeError: foo.classMethod is not a function
Foo.bar(); // "hanbaobao"
foo.fooName // "123"
foo._count // 0
/**父类的静态方法,可以被子类继承*/
class childFoo extends Foo{
}
childFoo.classMethod(); //'hello'
var childfoo = new childFoo();
childfoo.fooName //"132"
//静态方法可以用 super 关键字调用父级的静态方法
class childFoo2 extends childFoo{
static classMethod() {
return super.classMethod() + ', too';
}
}
childFoo2.classMethod() //"hello, too"
-
私有方法和私有属性
私有方法和私有属性是只能在类的内部访问的访问和属性,外部不能访问。ES6 目前不提供。只能通过变通方法模拟实现。
目前有提案为 class 添加私有属性,方法是在属性名之前,使用 # 表示。
私有属性不限于从 this
引用,只要是在类的内部,实例也可以引用私有属性。
私有属性和私有方法前面,也可以加上 static
关键字,表示这是一个静态的私有属性或私有方法。
现有的解决办法:(可能实际中很少应用)
(1)约定俗成,在变量前加上下划线"_"前缀,约定这是一个私有属性;但实际上,它仍然是一个穿上皇帝新衣般的公共属性。
(2)索性将私有方法移出模块,因为模块内部的所有方法都是对外可见的。
(3)利用Symbol
值的唯一性,将私有方法的名字命名为一个Symbol
值。
-
new.target 属性
new 是从构造函数生成实例对象的命令。ES6 为 new 命令引入了一个 new.target 属性,该属性一般用在构造函数之中,返回
new 命令作用于的那个构造函数。若构造函数不是通过 new 命令或 Reflect.construct() 调用的,new.target 会返回 undefined,
因此这个属性可以用来确定构造函数是如何调用的。
(1)new.target 属性可以确定构造函数如何调用
(2)Class内部调用 new.target,返回当前Class。
(3)子类继承父类是,new.target 会返回子类。利用此特性,可以写不能独立使用,必须继承后才能使用的类
(4)在函数外部,使用 new.target 会报错。
/*new.target 属性可以确定构造函数如何调用*/
function Person(name) {
if (new.target !== undefined) {
this.name = name;
} else {
throw new Error('必须使用 new 命令生成实例');
}
}
var person = new Person('张三'); // 正确
var notAPerson = Person.call(person, '张三'); // Uncaught Error: 必须使用 new 命令生成实例
/*Class 内部调用new.target,返回当前 Class。*/
class Rectangle {
constructor(length, width) {
console.log(new.target === Rectangle);
this.length = length;
this.width = width;
}
}
var obj = new Rectangle(3, 4); // true
/*子类继承父类时,new.target会返回子类。**/
class Square extends Rectangle {
constructor(length, width) {
super(length, width);
}
}
var obj = new Square(3); // false
/*利用此特性可以用来写 不能独立使用、必须继承后才能使用的类。**/
class Shape {
constructor() {
if (new.target === Shape) {
throw new Error('本类不能实例化');
}
}
}
class Rectangle extends Shape {
constructor(length, width) {
super();
// ...
}
}
var x = new Shape(); // 报错
var y = new Rectangle(3, 4); // 正确