有人能解释一下我是怎么搞砸的,为什么它工作,我怎么能纠正它

Can someone please explain how I messed up, why it worked and how I can correct it

本文关键字:为什么 工作 怎么能 能解释 一下      更新时间:2023-09-26

我有一个奇怪的情况。就在最近,我一直试图改变一些代码从过程到基于对象由于之前的问题。

我在代码中有几个地方调用函数中的函数(请原谅,我还在学习Javascript的术语),因此'this'承担了不同的作用域。

在试图保持与父'this'的连接时,我试图通过向函数调用添加"thisObj = this"来将变量传递给函数,如下所示

geoLoc: function () {
    "use strict";
    var thisObj;
    if (navigator.geolocation !== undefined) {
        navigator.geolocation.getCurrentPosition(function (position) {
            thisObj.calcRoute('driving', position.coords.latitude + ', ' + position.coords.longitude, true);
        }, thisObj = this);
    }
},

所以,这与FF工作,所以我认为它一定是好的。用jslint检查,一切都是绿色的(或黄色/蓝色),没有任何错误。

Chrome浏览器决定有一个"不匹配dom异常17",并决定不与地理位置工作。

只是偶然的,我试着移动这个定义,使它读作

geoLoc: function () {
    "use strict";
    var thisObj;
    if (navigator.geolocation !== undefined) {
        navigator.geolocation.getCurrentPosition(function (position) {
            thisObj.calcRoute('driving', position.coords.latitude + ', ' + position.coords.longitude, true);
        }), thisObj = this;
    }
},

令我惊讶的是,这在FF和Chrome中都有效。不幸的是,它失败了,jslint和IE只是踢了它的脚跟,然后死了。

现在,我的问题是,我到底做了什么,让它与FF一起运行,并传递jslint,以及我如何纠正这种情况,而不诉诸于在第二个函数中实际命名对象,所以我可以传递对它的引用。

请不要使用jquery。直javascript。比修复它的代码更重要的是,解释我实际上做了什么……如果可能的话,请用外行的话,以便我能进一步调查。

在Javascript中,你不需要到处传递变量,因为函数可以访问它上面的函数中声明的变量。因此,您可以在名为that的变量中保存对当前对象this的引用(仅为示例),如下所示:

geoLoc: function () {
    "use strict";
    var that = this;
    if (navigator.geolocation !== undefined) {
        navigator.geolocation.getCurrentPosition(function (position) {
            that.calcRoute('driving', position.coords.latitude + ', ' + position.coords.longitude, true);
        }/* if you try to "add" something there, it comes as a 2nd argument for getCurrentPosition*/);
    }
},

你也可以说内部函数(s)"包含"外部函数的作用域,这是Javascript特有的,在它的设计和使用它设计应用程序时非常有趣。要了解更多信息,请查看JS中的"function scope"answers"closure"。

编辑: navigator.geolocation.getCurrentPosition中的第二个参数预计是一个错误回调,即一个函数,并且您试图将, thisObj = this放在那里,这可能会导致一些浏览器失败或-执行时-实际上在成功回调之前将this分配给thisObj (getCurrentPosition的第一个参数)被调用,因此在一些其他浏览器上"工作"。无论如何,这是不稳定的,应该避免。

我认为你需要从JS的基本语法特性开始,比如使用函数作为其他函数的变量和参数(这就是"回调"是什么),这是一个主要概念。而不是随机地尝试移动部分代码(我的意见)。