javascript - "use strict"时getBBox错误

标签 javascript d3.js strict

什么时候
“使用严格”;

对我的 D3JS 力网络图有效,我无法使用 this.getBBox(); 使用以下代码在力网络图中旋转边缘标签文本:

edgelabels.attr('transform',function(d,i){
  if (d.target.x<d.source.x){
    bbox = this.getBBox();
    rx = bbox.x+bbox.width/2;
    ry = bbox.y+bbox.height/2;
    return 'rotate(180 '+rx+' '+ry+')';
  }
  else { return 'rotate(0)'; }
});

如果我禁用 "use strict;",我的代码运行时不会出现错误,并且标签会正确旋转。 fiddle : https://jsfiddle.net/NovasTaylor/cnaqaxnh/

我的原始代码基于此 block : http://bl.ocks.org/jhb/5955887

如何将我的代码固定为使用 "use strict;" 与 getBBox() 或 getBBox() 的替代方法一起运行?

最佳答案

这里的问题不是getBBox(),而是缺少var:在非严格模式下,对未声明变量的赋值会认为该变量是全局变量.但是,这在严格模式下不起作用。

如果您查看 MDN page关于严格模式:

First, strict mode makes it impossible to accidentally create global variables. In normal JavaScript mistyping a variable in an assignment creates a new property on the global object and continues to "work" (although future failure is possible: likely, in modern JavaScript). Assignments which would accidentally create global variables instead throw in strict mode. (emphasis mine)

所以,而不是:

edgelabels.attr('transform', function(d, i) {
    if (d.target.x < d.source.x) {
        bbox = this.getBBox();
        rx = bbox.x + bbox.width / 2;
        ry = bbox.y + bbox.height / 2;
        return 'rotate(180 ' + rx + ' ' + ry + ')';
    } else {
        return 'rotate(0)';
    }
});

应该是:

edgelabels.attr('transform', function(d, i) {
    if (d.target.x < d.source.x) {
        var bbox = this.getBBox();
        var rx = bbox.x + bbox.width / 2;
        var ry = bbox.y + bbox.height / 2;
        return 'rotate(180 ' + rx + ' ' + ry + ')';
    } else {
        return 'rotate(0)';
    }
});

这是更新后的 fiddle :https://jsfiddle.net/onnoqyp4/

关于javascript - "use strict"时getBBox错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47763791/

相关文章:

javascript - 我可以在空数组中搜索吗?

javascript - 向力导向布局添加新节点

node.js - JavaScript 和分号

javascript - 我如何比较javascript中的2个函数

javascript - 平滑地理位置的噪声

javascript - 流中的条件类型

javascript - 动态改变 d3.js 桑基图的宽度

javascript - D3.js:不连续时间尺度(金融数据)

haskell - Haskell `seq` 算子的时间成本

mysql - 一般错误 : 1364 Field 'xxxx' doesn't have a default value