ES2015 类中的静态方法

在ES2015中,终于不用用函数原型来实现类系统,可以直接使用关键字class,下面是对class的静态属性的研究:

举例:一个Node类,每一个Node类之间都可以建立从属关系,每一个Node实例下方可以带多个Node子实例,Node自身可以检索到所有实例的数量。

首先创建两个属性,他爹,和他的子孙

        this._parent = parent;
        this._children = new Set();

创建生孩子的方法:(创建子节点)

    createChild(){
        const node = new Node(this);
        this._children.add(node);
        return node;
    };

创建与孩子断绝关系的方法:(删除节点)

    removeFromParent() {
        this._parent._children.delete(this);
        this._parent = null;
    };

创建人口普查方法:(获取节点大小)

    get size() {
        let size = 0;
        for (const node of this._children) {
            size += node.size
        };
        size = size ? size + 1 : 1
        return size;
    };

创建家谱:(将根节点存储起来)

    static addRoot(root) {
        Node.roots = !Node.roots ? [root] : Node.roots.concat([root]);
    };

看看家族中一共多少人:(获取根节点的所有节点)

    static get size () {
        return Node.roots
        .map(root => root.size)
        .reduce((a,b) => a + b);
    }

整个程序代码为:

class Node {
    constructor(parent = null) {
        this._parent = parent;
        this._children = new Set();
        if (this.isRoot) {
            Node.addRoot(this)
        };
    }
    get isRoot() {
        return !this._parent;
    };
    createChild(){
        const node = new Node(this);
        this._children.add(node);
        return node;
    };
    removeFromParent() {
        this._parent._children.delete(this);
        this._parent = null;
    };
    get size() {
        let size = 0;
        for (const node of this._children) {
            size += node.size
        };
        size = size ? size + 1 : 1
        return size;
    };
    static addRoot(root) {
        Node.roots = !Node.roots ? [root] : Node.roots.concat([root]);
    };
    static get size () {
        return Node.roots
        .map(root => root.size)
        .reduce((a,b) => a + b);
    }
}

静态属性的好处在于可以为类本身定义一些方法,而不是实例的方法(原型链上)。

 

静态属性还有一个参数固化的功能:

先定义一个Animal

class Animal {
    constructor (family, species, hue) {
        this.family = family;
        this.species = species;
        this.hue = hue;
    };
    yell(){
        return `I'm ${this.species}`;
    };

再定义一个扩展的功能,传入扩展的功能函数和传给Animal的参数

    static extend(constructor,..._args) {//..._args为Animal中的参数
        return class extends Animal {
            constructor(...args) {
                super(..._args);
                constructor.call(this,...args);
            }
        }
    }
}

最后检查结果

const Dog = Animal.extend(function(name){
    this.name = name;
},'four_feet','dogy','woug');
const dog1 = new Dog('Doge');
dog1.yell();//woug
console.log(dog1.name);//Doge

由此可以看出可以给Animal类扩展任意功能然后赋值给一个新的类。在写可维护代码的时候至关重要。

 

posted @ 2018-03-01 15:03  KeepLearning_!  阅读(365)  评论(0编辑  收藏  举报