" /> " /> Learn Dash AJAX Dot Com -
Welcome to Learn Dash Ajax Dot Com

JavaScript..."prototype" or Just Add a Property or Method?

Thursday, March 27, 2008
Do I prototype my objects with my properties and methods or do I just add properties in the constructor?

Think of it this way. The "prototype" methods and properties are always a part of your objects. Create a property or method without the prototype keyword if you want to decorate an existing object. Why? Because the more you prototype, the heavier the object becomes, so... prototype carefully. I guess an exception to this is if you are creating a singleton class, prototyping is probably not necessary as it is not instantiated so just going this.SomeMethod = ... is fine. Anybody have comments on that?

The Prototype JS framework is great but all the "prototyping" creates heavier objects that inherently might not have been as heavy. As well by prototyping an inherent data type like Object, you risk breaking existing JavaScript code that tries to integrate with a framework like Prototype because it's "prototype"ed all these new properties and methods on HTMLElements or the Object inherent data types.

Having said all that, JavaScript frameworks are great for RAD deployment, but I still stick by my guns when I say that with lots of data and objects on a page, this heavily protoyped framework mindset definitely slows things down. See my original post.

Listen to NIN

This not tech related, but it's just good music (in my opinion).

If you're a fan of NIN (Nine Inch Nails), take a listen below. They've made some serious cash by separating themselves from their record label.


JavaScript, Objects, Callbacks and the "this" Pointer Issue

So for those of you who code JavaScript, you may have come across this problem before. You JS class' method calls a callback method that is in the same or another class. The callback method gets called and in that method there's a line like this.myProperty which for argument sake is set to "Great... not another hello world! example" . Accessing this.myProperty evaluates as undefined? Wait a minute... I set this already! The problem is the "this" reference becomes the event element which might be the document or it might be a DOM element. This is normal JavaScript functionality.

So how do we get around this? In every object constructor, we will create a property called "me". This variable must be in the class with the var keyword in front of it or else the "me" variable will be considered global scope and be overwritten by any other singleton class or class instance.

I believe that it was Douglas Crockford who first pointed this out, check out his site http://www.crockford.com.

Check it out in action below:

<html>

<head>

<script>

Singleton = new function() {

var me = this

this.funcName = "Singleton"

this.Test = function() {

setTimeout(this.Alert, 1000)

}

this.Alert = function() {

alert("The this pointer does not work! funcName = " + this.funcName)

alert("The 'me' variable works! funcName = " + me.funcName)

}

}

function InstanceClass() {

var me = this

this.funcName = "InstanceClass"

this.Test = function() {

setTimeout(this.Alert, 1000)

}

this.Alert = function() {

alert("The this pointer does not work! funcName = " + this.funcName)

alert("The 'me' variable works! funcName = " + me.funcName)

}

}

function init()

{

Singleton.Test()

var oClass = new InstanceClass()

oClass.Test()

}

</script>

</head>

<body onload="init()">

</body>

</html>

Some Debugging Tips

Here's my response to this article, Using Visual Studio to Debug Javascript in IE by kubben on codeproject.com

All studio products since Visual Studio 6 allow you to debug client-side JavaScript via F5 (debug) or by adding the keyword "debugger" to your JavaScript source.

I would not recommend enabling/disabling debugging in Internet Explorer (IE) as you might wonder sometimes why the debugger is not firing. Why would you disable it? Well believe it or not, tonnes of sites have JavaScript errors so it can become annoying if you're surfing the web.

I know it sounds obvious to enable debugging in Internet Explorer, but I've seen it happen to many people and they never bother to check the obvious. A better idea is to have a windows account on your machine (your developer account) that has IE setup to be in debug mode for developing web applications. As well set your cache in Internet Explorer to the lowest number of MB possible. Also set your IE cache options to check "Every visit to the page".

Also be wary when debugging a static HTML page. If you make changes to a static HTML page, it doesn't always get updated, even with the above caching options set. I get around this by adding a querystring and changing it whenever I make changes to the HTML page. This only applies to you current browser session. If you close the browser and open the page again, it should be updated.

There is also a cool tool called the IE Developer Toolbar that you might want to check out,

This is all great if you're debugging only IE (probably a corporate scenario), however in the wonderful world of the Internet, more than IE needs to be supported.

Yes, I know IE still dominates, but 15% or whatever Firefox is at these days, is still a lot of people and Mac users are all about Safari or Firefox. Basically you want as many people seeing your site and seeing your site well.

Sooo....

Firefox has a cool add-on called FireBug, as well as another cool tool called the DOM Inspector which comes with Firefox by default.


You also might want to look into JSDoc, http://jsdoc.sourceforge.net, and JSUnit, http://www.jsunit.net, for speeding up development in the long run because you have API docs to reference and creating code that follows a certain standard.

Cheers,
Nick ;)

JavaScript String Tips

Let's talk about string concatenation. I want to alert to the screen "I like emus"

var sEmu = "I"
sEmu += " like"
sEmu += " emus"
alert(sEmu )


results in "I like emus" from a JavaScript alert box

While this gives us the result we want it is not the most efficient. The above example is trivial, but let's say we want to keep concatenating 1000 times then alert sEmu.


// Initialize string to empty
var sEmu = ""

for (var counter = 0; counter < 1000; counter++)
{
sEmu += "I"
sEmu += " like"
sEmu += " emus"
}

alert(sEmu)


The above code keeps copying strings over and over to build the new sEmu (slow). The better approach would be to use an array then join all the strings with an empty space (fast).

var aEmu = []
for (var counter = 0; counter < 3000; counter++)
{
aEmu[counter++] = "I"
aEmu[counter++] = " like"
aEmu[counter++] = " emus"
}

alert(aEmu.join(''))

JavaScript Stuff

Well I decided to start a blog for web developers. Basically I'll post code snippets that I think are useful to other web developers out there.

So since this is just the beginning, I'll give some JavaScript basics, but still very useful.

  1. Don't add methods to inherent data types/objects unless you absolutely have to. Prototyping new methods slows down the creation of every instance of that inherent data type, e.g. adding a Trim() method to the string datatype. Instead create your own class via the Singleton pattern.

    e.g.
    var Strings = function ()

    {

    this.Trim : function(sText)

    {

    var sTrimmed = ""



    if (sText && sText.length)

    {

    sTrimmed =
    sText.replace(/^\s*/, "").replace(/\s*$/, "")

    }



    return sTrimmed

    }

    }



    var sNonTrimmed = " remove my white space via trim please "



    // results in "remove my white space via trim please"

    var sTrimmed = Strings .Trim(sNonTrimmed)

    At work we develop using a proprietary JavaScript framework that uses helper objects like the one above to avoid prototyping inherent data types and objects.

    Having said that frameworks like prototype and the Dojo Toolkit do this. I used script.aculo.us to revamp my portfolio a bit and it runs on top of prototype. I find that in terms of cross-browser stuff, a framework like this is ideal for web applications that do not rely on heavy DHTML.

    If you have a site that uses a lot of DHTML/AJAX such as a tree control, you're better off doing your own thing since code forks for cross-browserness slow down things.

  2. Don't use semi-colons at the end of each line of JavaScript. They are not required and it reduces the footprint of your script file. Use them sparingly. If you need to put several lines of code on one line use them. This usually is the case once a script has been obfuscated.
  3. Use shortcuts for creating new objects and arrays:

    // Long way
    var someArray = new Array()

    // Shortcut
    var someArray = []

    // Long way
    var someObject = new Object()

    // Shortcut
    var someObject = {}

    // Long way
    var reSomeRegex = new RegExp("\d+", "g")

    // Shortcut
    var reSomeRegex = /\d+/g

Well that's all for now.


AddThis Feed Button   Bookmark and Share