J'utilise Noeud v8.1.3référence Enregistrement d'une fonction de membre d'instance de classe rend champ libre
J'ai une classe Utility
dans le fichier 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();
Maintenant, dans mon autre fichier, quand je faire
const utility = require('./utility');
utility.getCurrentWeatherByLatLong(Number(latitude), Number(longitude))
.then((result) => {
console.log(result)
})
cela fonctionne très bien. Cependant, quand je fais
const utility = require('./utility');
const functionToCall = utility.getCurrentWeatherByLatLong;
functionToCall(Number(latitude), Number(longitude))
.then((result) => {
console.log(result)
})
Je reçois l'erreur: Cannot read property 'isValidLatitude' of undefined
.
Pourquoi cette erreur se produit-elle et comment puis-je la résoudre? Merci!
Ok qui a fonctionné. Pourquoi a-t-il perdu sa portée? et n'aurais-je pas dû lier 'functionToCall' à' utility'? –
@AyushGupta J'ai mis à jour ma réponse avec une meilleure explication. J'espère que cela répond à vos questions :) – dan
merci! Mais la chose est, quand je fais 'functionToCall = functionToCall.bind (utilitaire);' Je reçois cette erreur à nouveau –