JavaScript类中使用.bind(this)报错:Cannot read properties of undefined
问题修复:Geolocation API在类中存储经纬度的报错
错误原因分析
第一个报错:Cannot read properties of undefined (reading 'bind')
构造函数中this._getCurrentLocal().bind(this);写法错误:_getCurrentLocal()方法无返回值(默认返回undefined),你试图对undefined调用bind方法,必然抛出错误。同时这行代码并未实际调用_getCurrentLocal方法,属于无效操作。第二个报错:Cannot set properties of undefined (setting 'latitude')
navigator.geolocation.getCurrentPosition的成功回调是普通函数,浏览器环境下普通函数作为回调时,this指向全局对象window而非App类实例,因此无法访问实例上的latitude和longitude属性。
修复后的代码
class App { constructor() { // 绑定方法的this到实例,确保方法内部this指向正确 this._getCurrentLocal = this._getCurrentLocal.bind(this); // 初始化属性为null,避免undefined状态 this.latitude = null; this.longitude = null; // 调用获取地理位置的方法 this._getCurrentLocal(); } _getCurrentLocal() { // guard clause if (!navigator.geolocation) { console.log('no geo location'); return; } // 使用箭头函数作为回调,自动继承外层的this(App实例) navigator.geolocation.getCurrentPosition( (position) => { this.latitude = position.coords.latitude; this.longitude = position.coords.longitude; console.log('lat ', this.latitude, ' long ', this.longitude); }, () => { prompt('Could not get your location'); } ); } }
其他可选修复方案
如果不想用箭头函数,也可以通过以下方式解决回调的this问题:
- 提前保存实例的this
_getCurrentLocal() { if (!navigator.geolocation) { console.log('no geo location'); return; } // 保存实例的this到变量self const self = this; navigator.geolocation.getCurrentPosition( function (position) { self.latitude = position.coords.latitude; self.longitude = position.coords.longitude; console.log('lat ', self.latitude, ' long ', self.longitude); }, function () { prompt('Could not get your location'); } ); }
- 绑定回调函数的this
_getCurrentLocal() { if (!navigator.geolocation) { console.log('no geo location'); return; } navigator.geolocation.getCurrentPosition( function (position) { this.latitude = position.coords.latitude; this.longitude = position.coords.longitude; console.log('lat ', this.latitude, ' long ', this.longitude); }.bind(this), // 绑定回调的this到App实例 function () { prompt('Could not get your location'); } ); }
内容的提问来源于stack exchange,提问作者DntMesArnd
相关产品推荐
相关产品推荐

