Jump to content

object literals


skaterdav85

Recommended Posts

I'm trying to write my JS in a more object oriented fashion, and so i created an object that controls this panel on one side of my page. However, inside my object methods, if i want to refer to any properties, i have to prefix them with the name of my object, in this case, vpanel. For example, in my showPanel method, i can't say this.panel.slideDown(400). Anyone know why?Here is my code in a script block in the head of my document:

var vpanel = {	init : function(){		$('#anchor1').bind('click', vpanel.showPanel);		this.panel = $('#panel');	},	showPanel : function(){		vpanel.panel.slideDown(400);	},	hidePanel : function(){	}}window.onload = function(){	vpanel.init();}

Link to comment
Share on other sites

An object literal can't use this to refer to itself, unless you call it with a specific scope. The function.call method lets you choose which scope to run the function in. This isn't the most ideal solution, but it works:

var vpanel = {	init : function(){		$('#anchor1').bind('click', this.showPanel);		this.panel = $('#panel');	},	showPanel : function(){		vpanel.panel.slideDown(400);	},	hidePanel : function(){	}}window.onload = function(){	vpanel.init.call(vpanel); // call vpanel.init in the scope of the vpanel object}

There's a problem there with calling showPanel in the right scope though, you would need to pass a version of showPanel that is set to run in a certain scope and Javascript doesn't have an easy way to do that manually without using an external library. It looks like jQuery has the jQuery.proxy method to do that, so you could write it this way:$('#anchor1').bind('click', jQuery.proxy(this.showPanel, this));Then inside showPanel you can use this instead of vpanel.There are better ways to define objects and classes though, look through this for some information:http://www.howtocreate.co.uk/tutorials/javascript/objects

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...