Class类

Class类

在ES6中,class (类)作为对象的模板被引入,可以通过 class 关键字定义类。
class 的本质是 function。
它可以看作一个语法糖,让对象原型的写法更加清晰、更像面向对象编程的语法。

Class类声明
Class类表达式

提升

  • 函数声明会提升
  • class类不会提升

实例属性和方法

class Rectangle {
    // constructor
    constructor(height, width) {
    //实例属性
        this.height = height;
        this.width = width;
    }
	//实例方法
    get area() {
        return this.calcArea()
    }
    //实例方法
    calcArea() {
        return this.height * this.width;
    }
    }
}
const square = new Rectangle(10, 10);
console.log(square.area);

原型上的属性和方法

function foo(){
	//静态属性
	this.a='a'
	//静态方法
	this.state=function(){
	console.log(1)
	}
}
foo()

decorator

decorator 是一个函数,用来修改类的行为,在代码编译时产生作用。

//一个参数
//第一个参数 target,指向类本身。

function testable(target) {
    target.isTestable = true;
}
@testable
class Example {}
Example.isTestable; // true
//多个参数——嵌套实现

function testable(isTestable) {
    return function(target) {
        target.isTestable=isTestable;
    }
}
@testable(true)
class Example {}
Example.isTestable; // true

extends

通过 extends 实现类的继承。

class Child extends Father { ... }

super

子类 constructor 方法中必须有 super ,且必须出现在 this 之前。
防止构造函数的原型上的方法找不到this指向

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值