Understanding scope in object oriented JavaScript

JavaScript/Ajax 13 Comments »

When you think of the keyword this you probably assume it refers to the current instance of the class. This is true for most object oriented languages like C# and Java.

For example I could use the this keyword in C# like this:

class Cat {
	string _name;
	public Cat(string name) {
		this._name = name;
	}
}

In the above example you see this illustrated. In C# and Java, this always refers to the class instance.

So, knowing this you would probably assume the same would be true of JavaScript and it’s this keyword. This is, however, not the case. Like a lot of things about writing object oriented code in JavaScript, this behaves differently in some situations. this does not always refer to the class instance depending on how you use it.

function Cat(name) {
	this.Name = name;
}

In the above example it works just like our C# example but let’s look at a situation where things can go wrong if you are unaware of some rules.

var wrong = new WrongClass();
wrong.publicMethod();

function WrongClass() {
	this.publicProperty = 'props';
	this.publicMethod = function() {
		console.log('public method');
		privateMethod();
	};
	var privateMethod = function() {
		console.log('private method');
		console.log('public property equals ' + this.publicProperty);
	};
}

In my examples I am using the console object of Firebug to output my data.

So what is wrong with the above example? It looks like everything should work, right? Well, operating on the assumption that this always refers to class instance then the above code would be correct. We are, however, using JavaScript and shouldn’t be that surprised that it does things a little differently.

The output when publicMethod() is called would be:

>>> public method
>>> private method
>>> public property equals undefined

The reason this.publicProperty is undefined is because when entering the private method the scope of this changed. It no longer means the current instance of the class ‘WrongClass’ but it now means the current instance of the function ‘privateMethod’.

Another situation where the scope of this would change is when dealing with event handlers.

document.getElementById('button').onclick = function() {
	alert(this.id);
}

In the above example this would refer to the instance of the document element ‘button’. There are many cases of scope change that you need to be aware of when dealing with object oriented techniques.

Back to our ‘WrongClass’ example. I’ll show you how to make that example work the way you would have expected it to work in the first place.

var right = new RightClass();
right.publicMethod();

function RightClass() {
	var self = this;
	this.publicProperty = 'props';
	this.publicMethod = function() {
		console.log('public method');
		privateMethod();
	};
	var privateMethod = function() {
		console.log('private method');
		console.log('public property equals ' + self.publicProperty);
	};
}

You’ll see that in the above code I have declared a variable called self. I assign this to this variable. This allows me to then use ’self’ any time I want to refer to the class instance without worrying about scope.

You can call your variable anything you like but ’self’ seems to be a common practice. So, now in ‘privateMethod’ when ‘publicProperty’ is called using ’self’ it will output the proper value.

>>> public method
>>> private method
>>> public property equals props

kick it on DotNetKicks.com

Popularity: 18% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Update on the Twitter API

JavaScript/Ajax No Comments »

Firstly I would like to thank Wink Chin for sending me an email to let me know the link to the demo of the Twitter API was broken. I have fixed that so you should have no trouble previewing the code in action.

I haven’t done much work on the API lately but I have noticed a buzz around the blogosphere about Twitter and it looks like a good opportunity to revive the project. I hope to be posting more about the API in the near future and will hopefully have some updates and new features for you to play with.

The latest updates for the API are here and here and you can download the demo code here.

Popularity: 10% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Friday roundup for May2, 2008

ASP.Net, Fun, JavaScript/Ajax, Methodology No Comments »

Here is some highlights from this week.

Hijax
When I was originally writing the DOM Scripting book, its scope was very clear - it was to be an introductory work on JavaScript and the Document Object Model, with an emphasis on best practices. I made a conscious decision not to cover advanced topics like XMLHttpRequest.

But as the writing of the book progressed, Ajax really began to explode. It became clear that I’d have to at least mention the subject, even if I couldn’t cover it in detail. That’s where the book’s final chapter came from.

Jason Calacanis, Please Help Me Become A Pathetic Affiliate Marketer
I’m hoping Jason Calacanis can help me out here. Everyone knows that Jason loves to stir up trouble at Internet conferences and he recently caused quite a stir at Affiliate Summit West a couple months ago when he referred to Zac Johnson’s $300,000 check from Yahoo as pathetic.

Simple Subverison Repository Setup with VisualSVN Server
I have a few projects I am developing for my own company and choosing source control has really not needed much discussion. I use Subversion for everything because it’s free, works really well, has great community support and support a wide-variety of clients on many operating systems.

Why I’m a better software developer than you
What makes one developer better than another? Shouldn’t we all be performing at the same level? Of course not, we’re not sewing buttons on an assembly line. We’re using every bit of our intelligence to create something that we can only begin to understand.

Popularity: 17% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Friday roundup for April 25, 2008

ASP.Net, Browsers, JavaScript/Ajax, SQL, Silverlight, XHTML/CSS No Comments »

Here is what I liked this week. Enjoy!

Comparing Popular JavaScript/Ajax Frameworks
After four days of ASP.NET AJAX training with Stephen Walther I set out to learn more about my options in choosing a solution for a JavaScript/Ajax framework. If I realized days later I would be writing this comprehensive post on 7 of the most popular frameworks, I may have just went with the “Inny-Minny-Miney-Moe” method!

jQuery AJAX calls to a WCF REST Service
Since I’ve posted a few jQuery posts recently I’ve gotten a bunch of feedback to have more content on using jQuery in Ajax scenarios and showing some examples on how to use jQuery to cut out ASP.NET Ajax. In this post I’ll show how you can use jQuery to call a WCF REST service without requiring the ASP.NET AJAX ScriptManager and the client scripts that it loads by default. Note although I haven’t tried it recently the same approach should also work with ASMX style services.

SQL SERVER - Better Performance - LEFT JOIN or NOT IN?
First of all answer this question : Which method of T-SQL is better for performance LEFT JOIN or NOT IN when writing query? Answer is : It depends!

Video: Write Your First Silverlight Game
In this video, I demonstrate how to start writing your first Silverlight game. I show how to create a dramatic space scene, add a soundtrack, and associate movement with the mouse wheel. This is the first part of a two-part series.

Reading binary files using Ajax
But when it comes to binary files, helping hands from server-side technologies are often necessary.

So I googled around to see what I can do about binary files with Ajax and found this Marcus Granado’s post at http://mgran.blogspot.com/2006/08/downloading-binary-streams-with.html

What he posted there worked like a charm for FireFox and Safari but I couldn’t get it to work for IE.

But luckily, within the same page, someone had posted up a solution for IE as a comment, which is written in VBScript.

Safari CSS Masks
Webkit continues to impress with it’s early implementations of new standards. WebKit now supports alpha masks in CSS. Masks allow you to overlay the content of a box with a pattern that can be used to knock out portions of that box in the final display. In other words, you can clip to complex shapes based off the alpha of an image.

Popularity: 36% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Friday Roundup for April 18, 2008

JavaScript/Ajax No Comments »

It’s been a slow week for me as far as reading and blogging goes but here are a few bits from this week.

Javascript: Introducing Using (.js)
The goals of using.js are to:

  • Seperate script dependencies from HTML markup (let the script framework figure out the dependencies it needs, not the designer).
  • Make script referencing as simple and easy as possible (no need to manage the HTML files)
  • Lazy load the scripts and not load them until and unless they are actually needed at runtime

You’re Fat and I Hate You
It irritates the hell out of me that so much modern JavaScript development hinges on frameworks. Not because there’s anything wrong with that in pragmatic terms, but because I’m interested in the mechanics of things, and programming with frameworks obscures the mechanics.

Popularity: 11% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Friday roundup for April 4, 2008

ASP.Net, Browsers, JavaScript/Ajax, SEO/Marketing, XHTML/CSS No Comments »

Here are some interesting stories from this week.

IE 8 strict mode doesn’t allow for CSS opacity?
So the fact that this has been labeled as by design suggests that IE8 will be the only browser produced in the last 10 or so years that will not support opacity in its strictest mode. Thats rediculous.

Google Will Sell Performics, SEOs Exhale
Exciting news from The Official Google blog today that reveals Google will stop scaring SEOs everywhere and will sell off Performics, the search marketing company that they accidentally acquired when they bought DoubleClick last year. To avoid the conflict of interest that comes when you’re a search engine selling search engine optimization services, Google will split Performics into two companies – an affiliate marketing company and a search marketing company – and then sell the search marketing half.

Webforms is dead. Long live MVC!
Scott Hanselman’s fourth screencast *confirms* that the interfaces and abstractions made as part of the MVC (HttpContextBase, IHttpRequest, IHttpResponse, etc.) will not be put into the existing Webforms model. That means that once MVC is released, the old HttpContext object in WebForms will *not* inherit from HttpContextBase, nor will the WebForms versions of HttpRequest and HttpResponse objects implement the interfaces.

But I’m not moving my mouse!
The IE team reacted correctly: the bug has been solved in IE8b1. When the mouse does not move any more the mousemove event stops firing, as it should.

However, this same bug was recently introduced in Safari (Windows) and Opera!

Safari 3.0 and Opera 9.26 support mousemove correctly, but Safari 3.1 and Opera 9.5b have copied the IE bug.

Popularity: 40% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

JavaScript defining and using custom events

JavaScript/Ajax 1 Comment »

kick it on DotNetKicks.com

What are custom events?

Simply, a custom event is something that happens that you feel is important enough to define actions to execute when this something happens. Clear as mud? I think I confused even myself. A custom event is just like a native event (onclick, onload, etc) except you define what it is and when it should fire.

Dustin Diaz explains custom events extemely well in his post about JavaScript custom events.

So why am I posting about it too? Well Dustin’s explaination and implementation uses the Yahoo User Interface library (YUI). I don’t use YUI. So I wrote up a simple class that allows you to implement custom events that is library independent.

The class

Here is the JavaScript class that is the base for our custom events.

var CustomEvent = function() {
	//name of the event
	this.eventName = arguments[0];
	var mEventName = this.eventName;

	//function to call on event fire
	var eventAction = null;

	//subscribe a function to the event
	this.subscribe = function(fn) {
		eventAction = fn;
	};

	//fire the event
	this.fire = function(sender, eventArgs) {
		this.eventName = eventName2;
		if(eventAction != null) {
			eventAction(sender, eventArgs);
		}
		else {
			alert('There was no function subscribed to the ' + mEventName + ' event!');
		}
	};
};

So here we have a class that defines the name of the event, subscribes a function to use, and a method to fire the event. Pretty simple.

Simple example

Here is a simple example of how to setup a custom event.

var myEvent = new CustomEvent("my event");
myEvent.subscribe(function(sender, eventArgs) {
	alert(eventArgs.message);
});

The above code creates an instance of CustomEvent and assigns a name of “my event”, how creative :D. Then it subscribes a function to the event via the subscribe method. The function that is subscribed will display an alert box with the value of the message event argument. The sender and eventArgs get passed when the event is fired. We’ll look at this next.

Firing the event

Finally we will fire the event. This can be done from anywhere in your application.

myEvent.fire(null, {
	message: 'you just witnessed the firing of a custom event called ' + this.eventName + '!'
});

We assigned a value of null to the sender argument because there is nothing that initiated the event fire in this case. If you had created this event in a photo gallery application and the event was to fire whenever a photo was inlarged (onEnlarge?) you would probably make the sender the photo that was enlarged. This would allow you to pass the photo to your enlarge method from inside the event. The possibilities are endless.

And lastly we assigned a value to message. Note that eventArgs is a JavaScript object (either { } or new Object()). This is important so you understand how to assign eventArgs properly.

Happy event creating.

Popularity: 21% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Friday roundup for March 28, 2008

ASP.Net, Browsers, JavaScript/Ajax, News 1 Comment »

Here is what I found interesting this week.

Key events and Safari 3.1
There has been a change in Safari 3.1 for how keypress events are handled. John Resig interviewed Yehuda Katz to get the skinny and understand why this was done.

eBay Discriminates Against Ebook Sellers, Squashes All Digital Downloads
In what will go down in Internet history as probably one of the lamest decisions ever in e-commerce, running second only to the firing of AOL CEO Jon Miller in 2006, eBay announced yesterday it will no longer allow any digitally downloadable product to be sold via an auction.

Where’s my .NET 3.5 (on IIS), Dude?
The not so obvious ‘problem’ is that if you fire up a machine that has .NET 3.5 installed, you might be surprised to find that the IIS service panel’s ASP.NET does not show an option to select the .NET Runtime of 3.5.

Opera and WebKit pass Acid3 test
The latest builds from Opera and WebKit are scoring a perfect 100/100 on the Acid3 test. Wow!

Where is Firefox on Acid 3? Here.
Some people have been surprised to not hear much from Mozilla around Acid 3. WebKit and Opera are duking it out, but what about Firefox?

Mike Shaver of Mozilla has posted on his views that Acid 3 is a missed opportunity and is pretty damning of the whole thing.

Using the YouTube API via Ext
With the YouTube API recently released, there’s bound to be lots of cool controls coming out soon. Thorsten Suckow-Homberg spent a weekend hacking up a Ext-based user extension that leverages YouTube’s chromeless API to build The Ext.ux.YoutubePlayer.

20 Types of Pages that Every Blogger Should Consider
When you use WordPress you’re given the choice when publishing between doing it as a ‘post’ or as a ‘page‘. Posts go up on your blog while ‘pages’ are static pages that you can publish without it having to go up on your blog.

Popularity: 25% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Base2: A Standards Based JavaScript Library

JavaScript/Ajax No Comments »

I’ve posted about Dean Edwards‘ Base2 library in the past but I wanted to write a post that brings all the growth Base2 has under gone over the last couple of years into a brief overview of the project so it is easy to see the progress Dean has made and where the project is headed.

In early 2006 Dean Edwards began a little project called Base. This was he first attempt to ease the pain of developing Object Oriented JavaScript.

I want a nice base class for JavaScript OO:

  • I want to easily create classes without the MyClass.prototype cruft
  • I want method overriding with intuitive access to the overridden method (like Java’s super)
  • I want to avoid calling a class’ constructor function during the prototyping phase
  • I want to easily add static (class) properties and methods
  • I want to achieve the above without resorting to global functions to build prototype chains
  • I want to achieve the above without affecting Object.prototype

About one year later Dean released the next iteration, Base2. Although Base was a fairly simple library to use there was no documentation. Other than Dean’s, very helpful, posts on his website there was nothing you could refer to in the traditional reference sense.

In August of 2007 there appeared a nice post on Dean’s site that annouced the arrival of some documentation for Base. Although it is stamped as currently incomplete (at the time of this article anyways) it is a huge boost for the library and the community that has grown around it.

In early 2008 Dean released some improvements for Base2 and some nice code examples further demonstrating what the library can do to make developer’s lives easier.

One thing that, I believe, makes Base stand out, and Dean as an excellent programmer, is his commitment to standards. Base adherse to some fundamental OOP rules, which Dean has outlined in a nice reference guide for library developers.

Base has enjoyed great admiration in the JavaScript community with other libraries using it as a starting point for their library cores.

Thanks Dean for the great leadership you bring to the web development community and keep up the great work.

Popularity: 19% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Method overloading in JavaScript

JavaScript/Ajax No Comments »

If you have been programming for any length of time you probably know what method overloading is or have at least heard of it.

What is method overloading?

Method overloading is a feature found in various object oriented programming languages such as C#, C++ and Java that allows the creation of several functions with the same name which differ from each other in terms of the type of the input and the type of the output of the function.

[Wikipedia]

With the formalities out of the way, there are times when method overloading can be very helpful. JavaScript is no exception. The problem is it is not as apparent how to achieve method overloading in JavaScript because it doesn’t work the same as more traditional languages do.

What won’t work

Let’s look at implementing an overloaded function how you would think it should work.

function myFunction() {
  //function with no arguments
}

function myFunction(arg) {
	//overloaded function with one argument
}

Now JavaScript will accept this and you may think you are done. Think again. You do not have an overloaded function. In the above example your second function definition just overwrote the first so you only have a function that excepts one argument. I told you it doesn’t work the same.

What will work

Now that we have looked at what won’t work let’s take a look at the proper way to implement an overloaded function.

Let’s look at a simple example using bunnies. Awww, how cute.

function getBunnyColor() {
	var name = arguments[0] == null ? 'peter' : arguments[0];
	switch(name) {
		case 'peter':
			return 'brown';
			break;
		case 'flopsy':
			return 'white';
			break;
		default:
			return 'unknown bunny';
			break;
	}
}

getBunnyColor(); //-> 'brown'
getBunnyColor('flopsy'); //-> 'white'

What is that?

Now I’ll explain what I did. Every function has an array called arguments. This array contains the arguments that are passed into the function even if specific arguments are declared in the function definition.

So knowing that I didn’t bother to declare any arguments when I defined the function. I instead used the arguments array to detect what had been passed in. If arugments[0] was null (no argument had been passed) then I assigned a default name of ‘peter’.

Conclusion

So JavaScript implements method overloading a bit differently than most languages meaning your function definitions will look different but you use the overloaded functions the same way. Hope this helps you out!

Popularity: 17% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.
WP Theme & Icons by N.Design Studio
Entries RSS Login