我有这样的代码,不知道为什么在传递给 nv.addGraph() 的匿名函数中我无法从外部函数访问变量,例如 a、zcls 或 this.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)中的工作方式不同。它的值是在运行时确定的,并且完全取决于我们调用函数的方式。
调用函数有四种不同的方式:
构造函数调用:使用new关键字;这是指新创建的实例
函数汽车 = 函数(){//... } var car = new Car();
函数调用:调用在某个范围内定义的函数时,例如全局范围。在本例中,this 指的是全局对象
函数 someFunc(){} someFunc();
方法调用:调用定义为对象成员的函数时。例如
var obj = { func: function(){} } obj.func();
在本例中,this 指向对象本身。
4 调用/应用:最后,可以借助 Function 构造函数原型(prototype)上定义的两个方法来调用函数。在这种情况下,我们可以自己自由设置它的值; var obj = { func: 函数(){} } 函数 someFunc(){}
someFunc.call(obj);
在您的情况下,为了访问 this.model
您需要显式定义 this 关键字指向的位置。
你必须选择:
- 定义一个局部变量,例如
var that = this;
使用 ES5
bind
方法nv.addGraph(函数() { ... }.bind(this));
关于JavaScript 闭包无法访问外部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21788785/