范围问题/“未定义不是一个函数”

Scope problems / "Undefined is not a function"

本文关键字:一个 函数 问题 未定义 范围      更新时间:2023-09-26

对于我的新项目,我正在学习使用Javascript中的对象。到目前为止,我已经把这一切搞得一团糟,希望有人能指出出了什么问题。

我的主要代码:

var self = null;    //to force a local 'self' variable from now on
var Person = function (firstName) {
    this.firstName = firstName;
    this.user_lat = 0;
    this.user_long = 0;
    this.user_accur = 0;
    this.user_stable = 0;       
};
Person.prototype.setCoordinates = function(lat, lng) {
    this.user_lat = lat;
    this.user_long = lng;
}
Person.prototype.fetchLocation = function() {
    var self = this;
    navigator.geolocation.getCurrentPosition(self.logPosition, function() { console.log("position fail") }, {enableHighAccuracy: true});
}

Person.prototype.logPosition = function(pos) {   //saves coordinates in current person - object
    this.setCoordinates(pos.coords.latitude, pos.coords.longitude);
}

index.php执行以下操作:

var person = new Person("Lorre");
person.fetchLocation();
//do_stuff_with_location_in_object

但是,"设置坐标"函数失败并给出错误:

Uncaught TypeError: undefined is not a function / main.js:40 / Person.logPosition

我很确定我做错了什么愚蠢的事情,但是我现在整个晚上都在为"这个"而苦苦挣扎,我越来越绝望了......希望你们中的任何一个人都能看到出了什么问题。

提前感谢!

感谢丹达维斯和迷你科技在评论中的帮助。 bind(this)做到了!

this.logPosition.bind(this)