2017-07-05 33 views
1

我使用節點v8.1.3存儲基準使其鬆動範圍

我在文件中有一類Utility現在utility.js

class Utility { 
    constructor() { 
     this.typeChecker = require('javascript-type-checker'); 
     this.internalErrors = require('../constants/internalErrors'); 
     this.axios = require('axios'); 
     this.config = require('../config'); 
    } 

    getCurrentWeatherByLatLong(latitude, longitude) { 
     if(!this.isValidLatitude(latitude)) throw this.internalErrors.ERR_LAT_INVALID; 
     if(!this.isValidLongitude(longitude)) throw this.internalErrors.ERR_LONG_INVALID; 
     const url = `${this.config.BASE_URL}?appid=${this.config.API_KEY}&lat=${latitude}&lon=${longitude}`; 
     return this.axios.default.get(url); 
    } 

    isValidLatitude(latitude) { 
     return (this.typeChecker.isNumber(latitude) && latitude >= -90 && latitude <=90); 
    } 

    isValidLongitude(longitude) { 
     return (this.typeChecker.isNumber(longitude) && longitude >= -180 && longitude <= 180); 
    } 
} 

module.exports = new Utility(); 

,我在其他文件中,當我做

const utility = require('./utility'); 
utility.getCurrentWeatherByLatLong(Number(latitude), Number(longitude)) 
     .then((result) => { 
      console.log(result) 
     }) 

它工作正常。但是,當我做

const utility = require('./utility'); 
const functionToCall = utility.getCurrentWeatherByLatLong; 
functionToCall(Number(latitude), Number(longitude)) 
     .then((result) => { 
      console.log(result) 
     }) 

我得到的錯誤:Cannot read property 'isValidLatitude' of undefined

爲什麼會發生此錯誤,我該如何解決它?謝謝!

回答

1

使用bind功能結合上下文:

constructor() { 
    this.typeChecker = require('javascript-type-checker'); 
    this.internalErrors = require('../constants/internalErrors'); 
    this.axios = require('axios'); 
    this.config = require('../config'); 
    this.getCurrentWeatherByLatLong = this.getCurrentWeatherByLatLong.bind(this) 
} 

this點上被調用函數的對象。所以,當你撥打utility.getCurrentWeatherByLatLong(...)時,thisutility。但是,當您撥打functionToCall(...)時,thisundefined

或者,因爲你已經在評論中建議,你可以綁定functionToCallutility

const utility = require('./utility'); 
let functionToCall = utility.getCurrentWeatherByLatLong; 
functionToCall = functionToCall.bind(utility); 
functionToCall(Number(latitude), Number(longitude)).then((result) => { 
    console.log(result); 
}) 
+0

好奏效。爲什麼它放寬了範圍呢?並且不應該將'functionToCall'綁定到'utility'? –

+0

@AyushGupta我用更好的解釋更新了我的答案。希望能回答你的問題:) – dan

+0

謝謝!但事情是,當我做'functionToCall = functionToCall.bind(工具);'我再次得到該錯誤 –