[英]Cannot read property of undefined. But property is a static function of an imported class
我正在粘贴整个堆栈跟踪
D:\Data\Documents\iBusFunctions\functions\objects.js:86
geohash = GeoHasher.encodeGeoHash({latitude: this.stop_lat,longitude: this.stop_lon});
TypeError: Cannot read property 'encodeGeoHash' of undefined
at Stop.createGeohash (D:\Data\Documents\iBusFunctions\functions\objects.js:86:29)
at D:\Data\Documents\iBusFunctions\functions\geohasher.js:72:35
at Array.forEach (<anonymous>)
at GeoHasher.init (D:\Data\Documents\iBusFunctions\functions\geohasher.js:63:24)
at Object.<anonymous> (D:\Data\Documents\iBusFunctions\functions\testGeohasher.js:23:4)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
有问题的 function 在 class 内的objects.js
中定义 像这样停止(省略构造函数,因为它有点大):
class Stop {
constructor(stop_id, stop_code, stop_name, stop_desc, stop_lat, stop_lon,zone_id, stop_url, location_type, parent_station, stop_timezone, wheelchair_boarding, level_id, platform_code){
// Omitted
}
createGeohash(){
this.geohash = GeoHasher.encodeGeoHash({latitude: this.stop_lat,longitude: this.stop_lon});
}
}
如代码所示, encodeGeoHash
function 来自另一个模块,该模块在objects.js
的开头导入,如下所示:
const {GeoHasher} = require('./geohasher');
最后geohasher.js
看起来像这样:
const Objects = require('./objects');
//Omitted
class GeoHasher {
//Omitted
static encodeGeoHash(geopoint) {
var is_even = 1;
var lat = [];
var lon = [];
var bit = 0;
var ch = 0;
var precision = 12;
var geohash = "";
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geohash.length < precision) {
if (is_even) {
let mid = (lon[0] + lon[1]) / 2;
if (geopoint.longitude > mid) {
ch |= BITS[bit];
lon[0] = mid;
} else
lon[1] = mid;
} else {
let mid = (lat[0] + lat[1]) / 2;
if (geopoint.latitude > mid) {
ch |= BITS[bit];
lat[0] = mid;
} else
lat[1] = mid;
}
is_even = !is_even;
if (bit < 4)
bit++;
else {
geohash += BASE32[ch];
bit = 0;
ch = 0;
}
}
return geohash;
}
//Omitted
}
exports.GeoHasher = GeoHasher;
我省略了一些导入和声明,以及 GeoHasher 和其他函数的构造函数。 class 工作正常。 我已经对其进行了测试,并且在所有这些测试中,encodeGeoHash 工作得非常好。 是因为我在 GeoHasher 中导入objects.js
吗? 我正在添加从断点获得的内容,这仅确认堆栈跟踪错误。
尝试访问 static 成员时,我收到了相同的错误消息。
// MyClass.js
export class MyClass {
static staticFunc(){
return "foo";
}
}
然后访问MyClass.staticFunc()
给出了完全相同的错误: Cannot read property of undefined.
对我来说,这是由于错误地导入了 class:
不正确:
import MyClass from "MyClass";
正确的:
import {MyClass} from "MyClass";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.