Skip to content
Advertisement

Javascript Object Confusion

I’ve confused myself nicely here. My scenario is as follows:

function DesignPad() {  
 function EditBar() {  
  ...  
  this.removeHandler = function() {  
    **// how do I call Dragger.removeAsset**  
  }  
 }  
 function Dragger(){  
  ...  
  this.removeAsset = function() {}  
 }  
 this.init = function() {  
  this.editBar = new EditBar();  
  this.dragger = new Dragger();  
 }  
}  

var dp = new DesignPad();  
...

I can’t seem to call Dragger.RemoveAsset. I understand the why, my question is how do I call it?

I’m trying to keep like-things separated (e.g. Dragger / EditBar) but I seem to get all sorts of mixed up in my event handlers. Any suggestions, good reading materials, etc. on this stuff?

Advertisement

Answer

I found Douglas Crockford’s Javascript to be the best introduction to JavaScript. Especialy videos for Yahoo, like: The JavaScript Programming Language where you can learn how exactly are objects created and inherited in JS.

Solution to you problem is:

function DesignPad() {  
  var that = this;
 function EditBar() {  
  this.removeHandler = function() {  
    print("RemoveHandler");
    that.dragger.removeAsset();
  }  
 }  
 function Dragger() {  
  this.removeAsset = function() {
    print("RemoveAsset");
  }  
 }  
 this.init = function() {  
  this.editBar = new EditBar();  
  this.dragger = new Dragger();  
 }
}  

var dp = new DesignPad();
dp.init();
dp.editBar.removeHandler();

But as others noticed you could refactor some things :).

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement