Syl Syl - 11 months ago 47
Javascript Question

Calling a JS class from a script tag

I have a class declared in a script imported before body:

$(document).ready(function(){

var FamilleTree = function() {
};
FamilleTree.prototype.someAlert=function() {
alert("test");
}
});


After that, I have the following code inside the body in a script tag:

$(document).ready(function(){
var famtree= new FamilleTree();
famtree.someAlert();
});


But when I load the page, here is the error from firefox:

ReferenceError: FamilleTree is not defined


The class is defined before the call, why is it not accessible ?

Answer Source

FamilleTree's scope is limited to the closure (the function inside document.ready). When you call from the other function the variable isn't in scope anymore. Try declaring FamilleTree outside the $(document).ready like this:

var FamilleTree = function(tree) {
  this.tree=tree
};

$(document).ready(function(){

  FamilleTree.prototype.drawTree=function() {
    $('#tree1').tree({
        data: this.tree,
        dragAndDrop: true
    });
  }
});