【问题标题】:Function scope error in javascriptjavascript中的函数范围错误
【发布时间】:2013-12-04 15:11:29
【问题描述】:

我有一个代码,它的作用如下

var Device = function(temp){
    this.list = temp;

    Device.prototype.getList = function(){
        return list;
    };

    Device.prototype.foo = function(tempFunc){
       navigator.geolocation.watchPosition( 
    function(pos) {
                //I want to call getList here so lets do it
                //Method No1 
                var list = this.getList();
                //Method No2
                var list = Device.prototype.getList();
                //Method No3
                var list = getList.call(Device)
            },
            funciton(){
              console.log("Error")
            }                         
    };
};

在所有三种方法中,我都遇到了错误。 1.object [object global] 没有get list 方法。 2.列表未定义 3.不能调用undefined。

我还尝试在此上下文中调用 foo 方法,然后在上下文中无法识别 pos,并且将 getList 作为参数传递也对我没有帮助。我想我确实了解这里的问题,但我不知道如何处理它。我需要在匿名函数中调用 getList 方法,但在全局上下文中调用该函数是我的想法。谁能帮我解决这个问题。

【问题讨论】:

    标签: javascript html callback scope


    【解决方案1】:

    首先,在构造函数内部构建原型属性通常不是一个好主意。

    function Device(temp) {
      this.list = temp;
    }
    

    您的“getList”函数必须显式检索接收者对象的“list”属性(this 的值):

    Device.prototype.getList = function() {
      return this.list;
    }
    

    最复杂的部分是设置回调函数,还好还不错:

    Device.prototype.foo = function(tempFunc){
       navigator.geolocation.watchPosition( 
           function(pos) {
             var list = this.getList();
             // ... whatever ...
           }.bind(this), // <-- the important part
           function(){
             console.log("Error")
           }
        );                     
     };
    

    .bind() 函数将为您提供一个预先安排了 this 的函数。

    【讨论】:

    • 你是天使..:) 我读到了 bind 出于某种原因我不理解 java-script 术语,不管我读了多少..非常感谢...
    猜你喜欢
    • 1970-01-01
    • 2018-07-07
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多