首页 > 解决方案 > 当我将其转换为类时,Javascript 代码不起作用

问题描述

我的代码的目标是显示包含一些标记的地图。

这段代码工作正常:

loadMarkers() { // charger la liste des markers en s'appuyant sur la liste des stations
    let req = new XMLHttpRequest();
    req.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Lyon&apiKey=b79a52a433adef0fc100cd73fedf36710122f4ab');
    req.addEventListener('load', function() {
        if (req.status >= 200 && req.status < 400) {
            mapbikes.contentstation(req.responseText);
        } else {
            mapbikes.contentstation(req.status);
        }

    });

    req.addEventListener('error', function() { // affichage d'un message d'erreur si jcdecaux ne répond pas.
        console.log("erreur de connexion");
    });

    req.send();
},

contentstation(response) { // affichage pour chaque marker, des inforamtions d'une station de vélos
    response = JSON.parse(response);
    response.forEach(function (info) {
        L.marker([info.position.lat, info.position.lng], {
            "jcdecauxInfo": info
        })
        .on('click', mapbikes.onMarkerClick) // Clic sur un marker
        .addTo(mapbikes.mapbikes)
        .bindPopup(
            `<div class="text-success"><h5>Station de Vélo'v</h5></div><h6>` +  info.name + `</h6>` +
            info.address + `<br>` + `<i class="fas fa-bicycle"></i>&nbsp;&nbsp;<strong>` + info.available_bikes + `&nbsp;vélo(s) disponible(s)</strong>`
        );
    });
},

但是当我在创建类时转换代码时,它就不起作用了:


class Mapbikes { // propriétés de la carte
    constructor() {
        this.lat = 45.757192;
        this.lng = 4.840495;
        this.zoom =  15;
        this.mapContainer = 'mapid';
        this.mymap = '';
        this.displayMap = '';
        this.addTo = '';
        this.idMap = 'mapbox.streets';
        this.accessToken = 'pk.eyJ1IjoiNzZzZWJhc3RpZW4iLCJhIjoiY2p3czd4dWNmMGtzbjQ5cDVscmhienQ2YyJ9.4jK_HgpV9ObUTqYmBeVtdg';
        this.layer = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}';
        this.attribution = 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
            '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
            'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>';
    }

    init() { // affichage de la carte de Lyon, vide
        this.mapbikes = L.map(this.mapContainer, {
            center: [this.lat, this.lng],
            zoom: this.zoom,
        })
    }

    display() {  // affichage du Layer mapbox.com
        L.tileLayer(this.layer, {
            id: this.idMap,
            maxZoom: 18,
            attribution: this.attribution,
            accessToken: this.accessToken,
        }).addTo(this.mapbikes);

        this.loadMarkers();
    }

    loadMarkers() { // charger la liste des markers en s'appuyant sur la liste des stations
        let req = new XMLHttpRequest();
        req.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Lyon&apiKey=b79a52a433adef0fc100cd73fedf36710122f4ab');
        req.addEventListener('load', function() {
            if (req.status >= 200 && req.status < 400) {
                Mapbikes.contentstation(req.responseText);
            } else {
                Mapbikes.contentstation(req.status);
            }
        });

        req.addEventListener('error', () => { // affichage d'un message d'erreur si jcdecaux ne répond pas.
            console.log("erreur de connexion");
        });

        req.send();
    }

    contentstation(response) { // affichage pour chaque marker, des inforamtions d'une station de vélos
        response = JSON.parse(response);
        response.forEach(info => {
            L.marker([info.position.lat, info.position.lng], {
                "jcdecauxInfo": info
            })
            .on('click', Mapbikes.onMarkerClick) // Clic sur un marker
            .addTo(Mapbikes.mapbikes)
            .bindPopup(
                `<div class="text-success"><h5>Station de Vélo'v</h5></div><h6>` +  info.name + `</h6>` +
                info.address + `<br>` + `<i class="fas fa-bicycle"></i>&nbsp;&nbsp;<strong>` + info.available_bikes + `&nbsp;vélo(s) disponible(s)</strong>`
            );
        });
    }

我在控制台中遇到了这个错误:

TypeError:Mapbikes.contentstation 不是函数

我已经尝试在 Mapbikes.contentstation(req.responseText); 上使用绑定。但它不起作用。

我该如何纠正这个?

谢谢

标签: javascript

解决方案


欢迎来到堆栈溢出,您可以尝试以下操作:

  loadMarkers() { // charger la liste des markers en s'appuyant sur la liste des stations
    const me = this;
    let req = new XMLHttpRequest();
    req.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Lyon&apiKey=b79a52a433adef0fc100cd73fedf36710122f4ab');
    req.addEventListener('load', function () {
      if (req.status >= 200 && req.status < 400) {
        me.contentstation(req.responseText);
      } else {
        me.contentstation(req.status);
      }
    }

你也可以尝试提供一个箭头函数作为你的回调,因为它会自动绑定到当前实例,但是箭头函数是 ES6 并且不是每个浏览器都支持


推荐阅读