函数不识别变量
Functions don't recognize variables
几天前我想在JavaScript中创建一个class时发现了prototypejs。
我有一些功能非常完美,可以绘制如下轮廓:
My Race Profile
要使用任何数据创建此配置文件,我想创建一个完整的 class。
这是我在 codepen.
上的代码
所以,解释一下我的问题:
我在我的构造函数中声明了我的变量。
当我使用 var rp = new RaceProfile('data.json', 'markers.json');
时,我没有任何问题。我所有的变量都是用好的值创建的。
但是,当我使用“rp.profile(data);
”时,之前声明的所有变量都是未定义的。似乎之前定义的所有值都被删除了。因此我的代码无法运行。
如果有人知道问题出在哪里,也请告诉我:)
当您说 "all the variables" 时,您是在谈论 "xScale"、"yScale" ... 吗?
因为这些变量无法在 profile 函数中访问,实际上 "var" 变量仅在其当前范围内可见({} 之间)。
要访问 class 函数中的变量,您必须使用 "this" 关键字,例如 dataProfile 字段:
var RaceProfile = Class.create({
initialize: function (dataProfile, dataCP) {
this.dataProfile = dataProfile;
this.dataCP = dataCP;
this.xScale = d3.scaleLinear();
}
现在您可以在其他函数中访问这些变量。
此外在 JS 中,默认 "this" 是上下文关键字,要了解更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
"this" 通过所有对象函数共享,但匿名函数有自己的 this(匿名函数不附加到您的对象)。
所以这行不通,您不能直接访问 xScale :
profile: function (rawData) {
d3.json(this.dataProfile, function (error, rawData) {
// ..
this.xScale.range([0, width]).domain(d3.extent(data, function (d) {
return d.distance;
}));
您必须将对象的 "this" 保存在变量中:
profile: function (rawData) {
var self = this;
d3.json(this.dataProfile, function (error, rawData) {
// ..
self.xScale.range([0, width]).domain(d3.extent(data, function (d) {
return d.distance;
}));
几天前我想在JavaScript中创建一个class时发现了prototypejs。 我有一些功能非常完美,可以绘制如下轮廓: My Race Profile
要使用任何数据创建此配置文件,我想创建一个完整的 class。
这是我在 codepen.
上的代码所以,解释一下我的问题:
我在我的构造函数中声明了我的变量。
当我使用 var rp = new RaceProfile('data.json', 'markers.json');
时,我没有任何问题。我所有的变量都是用好的值创建的。
但是,当我使用“rp.profile(data);
”时,之前声明的所有变量都是未定义的。似乎之前定义的所有值都被删除了。因此我的代码无法运行。
如果有人知道问题出在哪里,也请告诉我:)
当您说 "all the variables" 时,您是在谈论 "xScale"、"yScale" ... 吗? 因为这些变量无法在 profile 函数中访问,实际上 "var" 变量仅在其当前范围内可见({} 之间)。
要访问 class 函数中的变量,您必须使用 "this" 关键字,例如 dataProfile 字段:
var RaceProfile = Class.create({
initialize: function (dataProfile, dataCP) {
this.dataProfile = dataProfile;
this.dataCP = dataCP;
this.xScale = d3.scaleLinear();
}
现在您可以在其他函数中访问这些变量。
此外在 JS 中,默认 "this" 是上下文关键字,要了解更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
"this" 通过所有对象函数共享,但匿名函数有自己的 this(匿名函数不附加到您的对象)。
所以这行不通,您不能直接访问 xScale :
profile: function (rawData) {
d3.json(this.dataProfile, function (error, rawData) {
// ..
this.xScale.range([0, width]).domain(d3.extent(data, function (d) {
return d.distance;
}));
您必须将对象的 "this" 保存在变量中:
profile: function (rawData) {
var self = this;
d3.json(this.dataProfile, function (error, rawData) {
// ..
self.xScale.range([0, width]).domain(d3.extent(data, function (d) {
return d.distance;
}));