JavaScript 闭包无法访问外部变量

标签 javascript nvd3.js

我有这样的代码,不知道为什么在传递给 nv.addGraph() 的匿名函数中我无法从外部函数访问变量,例如 azclsthis.model

function (out) {
// Here you call the "this" means the widget instance. (@see Mylable.js)
var zcls = this.getZclass(),
uuid = this.uuid;

// The this.domAttrs_() means it will prepare some dom attributes,
// like the pseudo code below
/*
 * class="${zcls} ${this.getSclass()}" id="${uuid}"
 */
var a = this.domAttrs_();
out.push('<span ', this.domAttrs_(), '>fds</span><div id="chart"><svg></svg></div>');



nv.addGraph(function() {
    var chart = nv.models.multiBarChart()
    .transitionDuration(350)
    .reduceXTicks(true)   // If 'false', every single x-axis tick label
    // will be rendered.
    .rotateLabels(0)      // Angle to rotate x-axis labels.
    .showControls(true)   // Allow user to switch between 'Grouped' and
    // 'Stacked' mode.
    .groupSpacing(0.1)    // Distance between each group of bars.
    ;

    chart.xAxis.tickFormat(d3.format(',f'));

    chart.yAxis.tickFormat(d3.format(',.1f'));

    var data = [{
        key: 'Some key',
        color: '#ff44ee',
        values: [{
            x: 1,
            y: 3
        }, {
            x: 3,
            y: 4
        }]
    }]

    d3.select('#chart svg').datum(data).call(chart);
//      d3.select('#chart svg').datum(this.model.data).call(chart);

    var someData = this.model.data;

    nv.utils.windowResize(chart.update);
    return chart;
});

此函数以某种方式在 ZKoss Widget 中使用,因此在此函数中可以像 this.model 一样访问其属性,但在内部匿名函数中则不可能。我不知道这有什么问题,我刚刚开始用 JS 编码。

最佳答案

JavaScript 中的 this 关键字与其他面向对象语言(例如 Java)中的工作方式不同。它的值是在运行时确定的,并且完全取决于我们调用函数的方式。

调用函数有四种不同的方式:

  1. 构造函数调用:使用new关键字;这是指新创建的实例

    函数汽车 = 函数(){//... } var car = new Car();

  2. 函数调用:调用在某个范围内定义的函数时,例如全局范围。在本例中,this 指的是全局对象

    函数 someFunc(){} someFunc();

  3. 方法调用:调用定义为对象成员的函数时。例如

    var obj = { func: function(){} } obj.func();

在本例中,this 指向对象本身。

4 调用/应用:最后,可以借助 Function 构造函数原型(prototype)上定义的两个方法来调用函数。在这种情况下,我们可以自己自由设置它的值; var obj = { func: 函数(){} } 函数 someFunc(){}

someFunc.call(obj);

在您的情况下,为了访问 this.model 您需要显式定义 this 关键字指向的位置。

你必须选择:

  1. 定义一个局部变量,例如var that = this;
  2. 使用 ES5 bind 方法

    nv.addGraph(函数() { ... }.bind(this));

关于JavaScript 闭包无法访问外部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21788785/

相关文章:

使用 "this = "的 Javascript 函数给出 "Invalid left-hand side in assignment"

javascript - 通过作为函数调用将 Props 传递给 React 类的正确方法

javascript - 使用 jQuery Bootgrid 方法

javascript - d3.js & nvd3.js -- 如何设置y轴范围

angularjs - 基本的 AngularJS NVD3 指令将不起作用且没有错误

javascript - NVD3 JavaScript 图表 - 使用 1 个或多个系列的具有重复右侧 y 轴的折线图

javascript - slideDown 强制显示 :block

javascript - 删除 HTML 中的部分标记

javascript - nvd3多条形图高度和标签问题

javascript - 未捕获的类型错误 : Cannot read property 'y' of undefined in NV D3 StackedLine