js类的使用

brush示例

以d3的一个brush进行叙述,示例见:

https://bl.ocks.org/xunhanliu/6f0b46789842e9e19e6cfe9bd0b16806

应用情形:

当页面上有多个图时,况且每个图维护一份brush,互不影响。

js 类的基本结构:

//定义类
var a=100; class Point { constructor(x, y) { this.x = x; this.y = y;
} toString() {
return '(' + a + this.x + ', ' + this.y + ')'; //全局变量a,仍正常使用 } }

 参考自:https://www.cnblogs.com/zczhangcui/p/6528039.html

说明:

1、constructor:是构造方法

2、类中每个方法前面不许加function。

3、全局变量可正常使用

重点:

this冲突

this在事件中(element)有特定的指定的(谁的函数触发的这个函数,这个函数内部的this就指向谁(dom))。而且在全局区域中使用this,this指向window类。

当然在自定义的类中常只存在事件绑定的方法(如click事件绑定了此类的一个方法)中this的冲突。针对这种情况,可使用闭包来避免。

如:

       class Point {
        constructor(dom) {
            d3.select(dom).on('click', this._click(this));
        }

        _click(that) {
            return function () {
                //在里面 this指向被点击的元素,that指向Point实例  
            }
        }
    }

 

posted @ 2019-06-08 13:59  xunhanliu  阅读(3567)  评论(0编辑  收藏  举报