Why I can't call to public function in a Javascript namespace

I want to call to method setupCanvas.Draw(); to draw rectangle.

And for some reason I can not call a function Draw(); from out the scop game.setupCanvas(); Demo jsfiddle

window.game = window.game|| {};
game.main = function() {};      
game.setupCanvas = function(){

        var w = $(window).outerWidth();
        var h = $(window).outerHeight();
        myCanvas = document.createElement('canvas');
        document.body.appendChild(myCanvas);
        myCanvas.id     = "playground";
        myCanvas.width  = w * 0.8;
        myCanvas.height = h * 0.8;
        myCanvas.style.left= (w - myCanvas.width )/2 + 'px' ;
        myCanvas.style.top= (h -  myCanvas.height )/2 + 'px' ;     
        myCanvas.style.zIndex   = 10;
        myCanvas.style.position = "absolute";
        myCanvas.style.border   = "1px solid green ";
        this.ctx= $('#playground').get(0).getContext('2d');

       this.Draw  = function(){
         ctx.fillStyle="#0000FF";
         ctx.fillRect(150,75,150,75);
         ctx.fillStyle="#F0F0FF";
         ctx.fillRect(0,0,150,75);
    };
}();    
    game.setupCanvas.Draw();

‚Äč

Many thanks

Answers


You need to create a new instance:

var x = new game.setupCanvas();

x.Draw();

Also, this part is wrong:

 };
}(); // <--

game.setupCanvas.Draw();

You're immediately-invoking the function, which you shouldn't be doing. It returns undefined to game.setupCanvas. Take it away and your code should work.

Moreover, when you reference a thectx property in your Draw method, you need to use this.ctx.

jsFiddle Demo


Need Your Help

Combine two variables conditionally

r date

visit_1=as.Date(c("2013-03-22", "2013-05-25", "NA", "2013-02-19", "NA", "2013-04-22", "2013-06-22", "2013-03-28", "NA", "NA", "2012-12-28" ) )

Internet Explorer 7 css/html float bug

html css internet-explorer-8 internet-explorer-7 css-float

The problem is a footer on a web page that seem to not follow the correct flow like it does in FireFox. The problem feels like it is an Internet Explorer related bug, because the layout will "magic...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.