Javascript 如何解决“cannot call method ... of undefined”错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10245779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:28:13  来源:igfitidea点击:

How to solve “cannot call method … of undefined” error?

javascriptgoogle-maps-api-3

提问by kamal

    function calcRoute() {
        var start = document.getElementById("start_").value;
        var end = document.getElementById("end_").value;
        var request = {
            origin: start,
            destination: end,
            travelMode: google.maps.TravelMode.DRIVING
        };
        directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
        });
    }

Gives an error message in Chrome: "Uncaught TypeError: Cannot call method 'setDirections' of undefined". Could anyone suggest fixing this? thanx

在 Chrome 中给出错误消息:“未捕获的类型错误:无法调用未定义的方法 'setDirections'”。有人可以建议解决这个问题吗?谢谢

采纳答案by The Alpha

You are missing (global var)

你不见了(全局变量)

//var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({ 'map': map }); 

So directionsDisplayis undefined.

所以directionsDisplay是未定义的。