Jump to content

OOP JavaScript


aspnetguy

Recommended Posts

Is it possible to make an object's or class' properties readonly? For example:

var myObject = {  param1: "param 1 value"}

By default param1 is not readonly because I can do this to change it's value

myObject.param1 = "custom value";

Similarly I would like to make a class' property readonly.

function myClass(){  this.param1 = "param1 value";}

Can I prevent that value from being chnaged like this,

var obj = new myClass();obj.param1 = "custom value";

Is this just the way JS is or can I preserve the property values?

Link to comment
Share on other sites

Hmm, so I ran a little test and came up with this:

<html><head><script type="text/javascript">function TestClass(){    var date = new Date();    this.getDate = function() { return date; }}var myTest;var display;function runTest(){    myTest = new TestClass();    display = document.getElementById("display");    display.innerHTML = myTest.getDate() + "<br />";    setTimeout("delayTest();", 10000);}function delayTest(){    myTest.date = new Date();    display.innerHTML += myTest.getDate() + "<br />";    display.innerHTML += myTest.date;}window.onload = runTest;</script></head><body><div id="display"></div></body></html>

Because I set up the "date" member with var, you can't access it outside of the class (TestClass). So, the only way you can get at that member is by calling the getDate method. However, when I called myTest.date = new Date();, a new public member was created called "date" and the new Date is stored in it. As you can see by the test, the "myTest.getDate()" method returns the untouched property while the "myTest.date" returns the newly created public property.When I run this code, it displays (after ten seconds) the following:

Wed Dec 06 2006 13:51:23 GMT-0800 (Pacific Standard Time)Wed Dec 06 2006 13:51:23 GMT-0800 (Pacific Standard Time)Wed Dec 06 2006 13:51:33 GMT-0800 (Pacific Standard Time)

It could be a start.

Link to comment
Share on other sites

Thanks Jesh, just one thing...the this,getDate is left open, I could easily change the function definition by just doing myText.getDate = fuinction(){} anf that changes the original member.Anyways it looks like I am out of luck on this.

Link to comment
Share on other sites

Thanks Jesh, just one thing...the this,getDate is left open, I could easily change the function definition by just doing myText.getDate = fuinction(){} anf that changes the original member.Anyways it looks like I am out of luck on this.
Bummer. I hadn't thought of that. :)
Link to comment
Share on other sites

aspnetguy, yeah, I know what you mean - but I have faith that IE8 will support the ECMAv4 revisions by the end of next year, it'd be silly not to really, especially with the current JS1 bugs and need for updates.Have you tried watch()? It's not great, and obviously you could just build an unwatch() over it, but combined with the others, it's another layer the person needs to get past before modifying your 'constant'.

Link to comment
Share on other sites

What would you need a read only object and variables for?
Maybe he's building a toolkit, and he doesn't want people messing around with important source variables. :)
Link to comment
Share on other sites

Maybe he's building a toolkit, and he doesn't want people messing around with important source variables. :)
That is exactly what I am doing. I'm not sure what the scope of the toolkit will be but I have made a nice querystring array object, finally no more parsing location.search! And a browser detect object. I am debating what to do next...I have an old GridView control I started maybe I'll port that into the toolkit. Any ideas? Things that are a pain to do (and are repetitive) that should be simplified?
Link to comment
Share on other sites

I am debating what to do next...Any ideas? Things that are a pain to do (and are repetitive) that should be simplified?
If you use AJAX, it helps to have a toolkit built for that. Maybe another one to add event listeners to the page so it's easy to add onclick (onmouseover, onload, onmousemove, etc.) handlers to the DOM.I like your Request.QueryString parser. Brilliant!
Link to comment
Share on other sites

a toolkit is a collection of JS functions and objects that you can reuse in all your projects.for example my toolkit has a function called $() which is just a shortcut to document.getElementById().So writing

var x = $('someId');

is the same as

var x = document.getElementById('someId');

except just much less code.

Link to comment
Share on other sites

Exactly :)
1. Can I help? Please? :)2. getElementsByClassName();3. creIframeDoc();4. var pageHTML=ajax("http://www.w3schools.com","page");5. Cookie functions, like PHP's. $_COOKIE['cookie'] or whatever. That would be so awesome, along with setCookie.1) Please? :)2) Simple. Get all elements with that className.3) Cross-browser. It would have two arguments:creIframeDoc(name,url);If the name argument is given, it creates an iframe and returns the document of it. Basically, you can then use x=creIframeDoc(name).If both the name argument and the URL argument are given, then it'll go to that iframe, change the URL, and return the iframe document.4) ajax(url,elId) would retrieve the HTML of the page specified by the variable URL. If elId is supplied, then it'll return the innerHTML of that element on the page you specified in URL.5) Self explanatory. Those are the ones I'd use the most. :blink:
Link to comment
Share on other sites

@aspnetguy - Here's an AJAX library I just put together for you. Feel free to add this to your Zoodles library - just add a little credit to my name, OK? :)I don't yet know how to attach files (can anyone explain to me how this is done?) so here it is in a codebox:

/*---------------------------------------------------- * Name: Jesh's Ajax Library * Version: 0.1 * Date: December 8th, 2006 * Author: Josh Sorem * Notice: For free use and redistribution with this *		   notice attached. * Copyright 2006-2007.  All rights reserved. *---------------------------------------------------- * Usage:	There are two ways to use this library - synchronously and asynchronously.  		Synchronously:	==============================================		// option 1	alert(Ajax.Get("http://theURL/thefile.ext").Text);		// option 2	var response = Ajax.Get("http://theURL/thefile.ext");	if(response.Status == 200)	{		alert(response.Text);	}	==============================================	Asynchronously:	==============================================	function myCallbackHandler(response)	{		if(response.Status == 200)		{			alert(response.Text);		}		else		{			alert("Error: " + response.Status + " " + response.StatusText);		}	}		Ajax.Get("http://theURL/thefile.ext", myCallbackHandler);	==============================================			To POST data, make sure that the data is in the following format: key1=value1&key2=value2		var data = "key1=value1&key2=value2";	Ajax.Post("http://theURL/thefile.ext", data, myCallback);*/// The main Ajax Object. var Ajax = new AjaxRequest();function AjaxRequest(){	// Private - This is the XMLHttpRequest object.    var _httpRequest = GetHttpRequestObject();        // Public - This method sends a GET request to a specified URL.    // If you specify a callback function, the request will go    // out asynchronously and your function will be called    // when the request has completed.  Otherwise, the script    // will wait for the response and return the Response object.	this.Get = function(url, callback)	{		if(_httpRequest)		{			if(callback)			{				_httpRequest.onreadystatechange = function() { HandleAjaxRequest(callback); };				_httpRequest.open("GET", url, true);				_httpRequest.send("");			}			else			{				_httpRequest.open("GET", url, false);				_httpRequest.send("");				return new AjaxResponse();			}		}	}	// Public - This method sends a POST request to a specified URL with	// the specified data.  If you specify a callback function, the	// request will go out asynchronously and your function will be	// called when the request has completed.  Otherwise, the script	// will wait for the response and return the Response object.	this.Post = function(url, data, callback)	{		if(_httpRequest)		{			if(callback)			{				_httpRequest.onreadystatechange = function() { HandleAjaxRequest(callback); };				_httpRequest.open("POST", url, true);				_httpRequest.setRequestHeader("Content-Type", "application/x-www-urlencoded");				_httpRequest.setRequestHeader("Content-Length", data.length);				_httpRequest.setRequestHeader("Connection", "close");				_httpRequest.send(data);			}			else			{				_httpRequest.open("POST", url, false);				_httpRequest.setRequestHeader("Content-Type", "application/x-www-urlencoded");				_httpRequest.setRequestHeader("Content-Length", data.length);				_httpRequest.setRequestHeader("Connection", "close");				_httpRequest.send(data);				return new AjaxResponse();			}		}	}		// Private - This is the Response object.  It's properties, as listed below, 	// are "Text" and "XML" which are the response data from the	// server (in text and xml formats respectively) and "Status" and	// "StatusText" which are the HTTP Status Code and HTTP Status Message	// from the server's response.	function AjaxResponse()	{		this.Text	= _httpRequest.responseText;		this.XML	= _httpRequest.responseXML;		this.Status			= _httpRequest.status;		this.StatusText		= _httpRequest.statusText;	}		// Private - This is the handler which listens for the onreadystatechange event	// of the XMLHttpRequest object.  This handler waits for the request 	// to end and then sends the AjaxResponse object to your callback function.	function HandleAjaxRequest(callback)	{		if(_httpRequest.readyState == 4)		{			callback(new AjaxResponse());		}	}		// Private - This function determines which method to use to set up the 	// XMLHttpRequest.  Should be cross-browser compatible.	function GetHttpRequestObject()	{			var object = false;		if(window.XMLHttpRequest)		{			object = new XMLHttpRequest();		}		else if(window.ActiveXObject)		{			try			{				object = new ActiveXObject("Msxml2.XMLHTTP");			}			catch(e)			{				try				{					object = new ActiveXObject("Microsoft.XMLHTTP");				}				catch(e)				{				}			}		}		return object;	}}

Examples on how to use it are in the script, but for clarity, here it is another example:

var myDiv = document.getElementById("myDiv");myDiv.innerHTML = Ajax.Get("http://theURL/thefile.ext").Text;

Link to comment
Share on other sites

getElementsByClassName is overkill imo, and encourages bad programming techniques.
Re bad programming habits--how?And @Jesh, that's amazing. Nice work. :)
Link to comment
Share on other sites

Re bad programming habits--how?And @Jesh, that's amazing. Nice work. :)
Jesh and Choco thanks for the ideasJesh I will definately use your code and give you credit :) and choco you can help :) I finished hte iframe contorl so it is easy to create read and write to an iframe.
Link to comment
Share on other sites

Jesh and Choco thanks for the ideasJesh I will definately use your code and give you credit :) and choco you can help :) I finished hte iframe contorl so it is easy to create read and write to an iframe.
Awesome. :)Maybe you should set up a CVS? :blink:
Link to comment
Share on other sites

I'll PM you monday, I have some ideas on organizing this thing.
Awesome. I'm starting a nice cookie object, and it's coming together well. It'll be accessed like this:Cookie.set("Name","expiration","value");And:Cookie.get("name");:)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...