2016-06-24 66 views
1

首先,我知道有數百萬這樣的問題。但我無法幫助我。Javascript Object Method Inaccessible/Undefined

我在加載所有圖像後調用繪製方法。正如你所看到的,當我嘗試訪問一個變量(loadedImages, this)內部繪製方法我得到了未定義。

爲什麼會發生這種情況,我如何得到這些變量?

var canvas = $('#area')[0], 
    context = canvas.getContext('2d'); 

function Character() { 
    return { 
     images: ["hair.png", "head.png", "mouth.png"], 
     loadedImages: {}, 
     init: function() { 
      this.loadImages(); 
     }, 
     loadImages: function() { 
      var loaded = 0, 
       imagesLength = this.images.length, 
       draw = this.draw; 

      for(var i = 0; i <= imagesLength - 1; i++) { 
       var image = new Image(), 
        bodyPart = this.images[i]; 

       image.onload = function() { 
        loaded++; 

        if(loaded == imagesLength) { 
         draw(); 
        } 
       }; 

       image.src = 'characters/Canser/' + bodyPart; 

       this.loadedImages[bodyPart.split(".")[0]] = image; 
      } 
     }, 
     draw: function() { 
      console.log(this); // undefined??? 
     } 
    }; 
} 

var canser = new Character(); 

canser.init(); 
+0

正是因爲你叫'draw'的方式! 'this.draw()'與'draw()'不同。 – deceze

+0

如果我這樣做,圖像對象將返回並沒有繪製方法。請參閱:image.onload –

+1

試着在你的上下文中理解'this'的'scope'。 (參考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) – lexith

回答

2
商店

這在並使用that.draw()

變種畫布= $( '#區域')[0], 上下文= canvas.getContext( '2D');

function Character() { 
    return { 
     images: ["hair.png", "head.png", "mouth.png"], 
     loadedImages: {}, 
     init: function() { 
      this.loadImages(); 
     }, 
     loadImages: function() { 
      var loaded = 0, 
       that = this, 
       imagesLength = this.images.length, 
       draw = this.draw; 

      for(var i = 0; i <= imagesLength - 1; i++) { 
       var image = new Image(), 
        bodyPart = this.images[i]; 

       image.onload = function() { 
        loaded++; 

        if(loaded == imagesLength) { 
         that.draw(); 
        } 
       }; 

       image.src = 'characters/Canser/' + bodyPart; 

       this.loadedImages[bodyPart.split(".")[0]] = image; 
      } 
     }, 
     draw: function() { 
      console.log(this); // undefined??? 
     } 
    }; 
}