javascript中的函数范围错误

时间:2013-11-20 14:51:00

标签: javascript html5 callback scope

我有一个代码,它的确如下

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.不能调用未定义的。

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

1 个答案:

答案 0 :(得分:3)

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

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的函数。