"use strict" 时出现 getBBox 错误

getBBox error when "use strict"

什么时候
"use 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;" 我的代码 运行s 没有错误并且标签旋转正确。 Fiddle: https://jsfiddle.net/NovasTaylor/cnaqaxnh/

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

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

这里的问题不是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/