JavaScript中的类class

参考文献

1. ES5中的近类结构

ES5中创建类的方法:

新建一个构造函数,定义一个方法并且赋值给构造函数的原型。

proto、prototype参考p21

//新建构造函数,大写字母开头
function Person(name) {
    this.name = name;
}
//定义一个方法并赋值给构造函数的原型
Person.prototype.sayName = function() {
    return this.name;
}
var p = new Person('Tom');
console.log(p.sayName());
复制代码

2. ES6中的class

ES6实现类很简单,只需要类声明。

class Person {
    //新建构造函数
    constructor(name) {
        this.name = name;//私有属性
    }
    //定义一个方法并赋值给构造函数的原型
    sayName() {
        return this.name;
    }
}
let p = new Person('Tom')
console.log(p.sayName())
复制代码

与ES5中使用构造函数不同的是,私有属性是实例中的属性,不会出现在原型上

类声明和函数声明的区别和特点:

1、函数声明可以被提升,类声明不能提升(与let声明类似)。

2、类声明中的代码自动强行运行在严格模式下。

3、类中的所有方法都是不可枚举的,而自定义类型中,可以通过Object.defineProperty()手工指定不可枚举属性。

4、每个类都有一个[[construct]]的方法。

5、只能使用new来调用类的构造函数。

6、不能在类中修改类名。

类表达式

类有声明式和表达式两种表现形式:

//声明式
class B {
    constructor(){}
}
//匿名表达式
let A = class {
    construnctor(){}
}
//命名表达式,B可以在外部使用,B1只能在内部使用
let B = class B1 {
    constructor(){}
}
复制代码

3. 类的应用场景

JavaScript函数是一等公民,类也设计成一等公民。

(1) 类作为参数传入函数

let A = class {
    sayName() {
        return 'Tom'
    }
}
//该函数返回一个类的实例
function test(classA) {
    return new classA()
}
//给test函数传A
let t = test(A)
console.log(t.sayName)
复制代码

(2) 通过立即执行函数,调用类构造函数创建单例

用new调用类的表达式,接着()调用表达式

let a = new class {
    constructor(name) {
        this.name = name
    }
    sayName() {
        return this.name
    }
}('Tom')
console.log(a.sayName())
复制代码

4. 类的静态成员

静态成员是指在方法名或属性名前面加上static关键字,和普通方法不一样的是,static修饰的方法不能在实例中访问,只能用类名直接访问。

class A {
    constructor(name) {
        this.name = name
    }
    static create(name) {
        return new A(name)
    }
}
let a = A.create('TOM')
console.log(a.name)//TOM
let t = new A()
console.log(t.create('Tom'))//t.create is not a function
复制代码

5. 继承与派生

比如自定义react组件要继承React.Component

class A extends React.Component {
    constructor(props){
        super(props)
    }
}
复制代码

A是派生类,在派生类中使用构造方法必须使用super.

关于super使用的几点要求:

  • 1、只可以在派生类中使用super。派生类是指继承自其它类的新类。
  • 2、在构造函数中访问this之前要调用super(),负责初始化this。

(1)在继承的类中重写父类方法

class Component {
    constructor([a,b] = props) {
        this.a = a
        this.b = b
    }
    add() {
        return this.a + this.b
    }
}
class T extends Component {
    constructor(props){
        super(props)
    }
    //重写父类方法add
    add() {
        return this.a * this.b
    }
}
let t = new T([2,3])
console.log(t.add())//6
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享