OOP in JavaScript - Part 4: Scoping

Permanent Link: OOP in JavaScript - Part 4: Scoping 21. Dezember 2009 Comment No Comment

I agree, it took me a while to write part 4 of my OOP in JavaScript series, but here it is now. As for the whole series, basic JavaScript knowledge is needed.

Scoping together with OOP is always an issue, when using asynchronous calls combined with callbacks. Let's create a very easy example where one method of a class registers an onclick EventListener and the second method of the class is the callback for the EventListener. The second method simply calls an alert with a message text defined in the class. Note that the Event Listener registration is not cross-browser safe:

function Handler()
{
}

Handler.prototype.messageText = 'You have clicked somewhere in the document';

Handler.prototype.registerAll = function()
{
window.addEventListener('click', this.handleOnclick, true);
}

Handler.prototype.handleOnclick = function(event)
{
alert(this.messageText);
}

var handler = new Handler();
handler.registerAll();

When clicking anywhere in the document you'd be expecting to see a message box "You have clicked somewhere in the document", but you only get a mesage box saying "undefined". Why is that?

The second argument of addEventListener() is the callback, it expects a function. By putting this.handleOnclick as callback, you are passing a copy of that function. It would be same if you had written it like this:

window.addEventListener('click', function() { alert(this.messageText); }, true);

As you can clearly see now the function stands for itself, this is not in the context(=scope) of the class Handler. In order to achieve exactly that, JavaScript gives us 2 possibilities: apply() and call(). Basically they are both the same, the only difference is in the way you pass further arguments. For a closer distinction, take a look at this page.

By passing an instance as first argument we are telling the function that is called in which scope to be executed, meaning: What instance is this? Let's alter the registerAll method of the example:

Handler.prototype.registerAll = function()
{
window.addEventListener('click', this.handleOnclick.apply(this), true);
}

When running your page now, you will notice that the alert puts out the right message, but is called the moment your page is rendered and the onclick event doesn't work anymore. This is because apply() and call() directly call the respecting function.

What we need to do, is to dynamically create a function that is called with the right scope when needed.

function Handler()
{
}

Handler.prototype.messageText = 'You have clicked somewhere in the document';

Handler.prototype.registerAll = function()
{
window.addEventListener('click', this.createOnclickHandler(), true);
}

Handler.prototype.createOnclickHandler = function()
{
var myScope = this;
return function(event) {
var handle = function(event) {
alert(this.messageText);
}
handle.call(myScope, event);
}
}

var handler = new Handler();
handler.registerAll();

Finally we get to see a "You have clicked somewhere in the document" message box only when clicking somwhere in the document. Note that the second parameter of call() is the Event Object, which is passed as first argument to the called function.

If using this is not total must for you, you can also throw away one of the functions and simply use myScope instead of this:

Handler.prototype.createOnclickHandler = function()
{
var myScope = this;
return function(event) {
alert(myScope.messageText);
}
}

serialize() vs. var_export() vs. json_encode() Memory Usage

Permanent Link: serialize() vs. var_export() vs. json_encode() Memory Usage 18. November 2009 Comment No Comment

Based on serialize() vs. var_export() vs. json_encode() Part 2, let's take a look at the (real) memory usage:

Apart from var_export allo methods seem to use about the same. Let's put the usage in relation to each other to get a better view:

With smaller arrays, the memory usage is exactly the same, from 10.000 elements on the values begin to diverge.

serialize() vs. var_export() vs. json_encode() Part 2

Permanent Link: serialize() vs. var_export() vs. json_encode() Part 2 17. November 2009 Comment No Comment

Based on the comments from my first benchmark in the serialize() vs. var_export() vs. json_encode article 2 days ago, I decided to benchmark once again, this time using different array sizes and I also added the JSON method with recursive UTF8 encoding beforehand. This time, all results are the combined results (exporting and importing), the testing script was exactly the same (except JSON+UTF8 which also had a utf8_encode_recursive function). Let's see what happens when using array sizes from 10 to 1000 elements:

So far, json_encode itself is fastest, closely followed by serialization. JSON with UTF8 Encoding is slowest, but consider that all the values are all below 0,02 seconds.

So far so good, let's look at the results with arrays from 10.000 to 1.000.000 elements:

Apart from the exception Serialization the values mostly develop like with smaller arrays. What's quite odd is that Serialization's runtime seems to be exploding when stepping up from 100.000 to 1.000.000. Why that is so, I cannot tell. Although JSON with UTF8 Encoding is slower than var_export and JSON itself, it's still way faster than serialization.

Conclusions

  1. None of the methods scales linear.
  2. For smaller arrays, JSON is the way to go, as long as your data is already UTF8 encoded. If not, you might want to take serialization.
  3. With larger arrays JSON is still fastest as long as your data is already UTF8 encoded, otherwise var_export is the best choice.

Closing, let's take a look at the graphs from 10 - 1.000.000 item large arrays:

serialize() vs. var_export() vs. json_encode()

Permanent Link: serialize() vs. var_export() vs. json_encode() 16. November 2009 Comment Comments (3)

There are times when you need to store an array, for example when your array is an index you wanna use again the next time you run your application. In order to store an array you have to transform it into some kind of string represantation first, most people would probably use serialize(). But there are also 2 other ways to achieve that: var_export() and json_encode().

After having them stored the functions to interpret the strings as arrays would be unserialize() if you use serialize(), eval() if you use var_export() and json_decode() if you use json_encode().

So, what about the performance?

In order to test that I wrote a little profiling script that first created some random array with 1.000.000 elements, then exported the array and then imported it again. For the json_encode() test the script looked like that:

$array = array_fill(0, 1000000, rand(1, 9999));

$start = microtime(true);
$export = json_encode($array);
$end = microtime(true);
$duration = $end - $start;
print('JSON Encode: ' . $duration . PHP_EOL);

$start = microtime(true);
$import = json_decode($export);
$end = microtime(true);
$duration = $end - $start;
print('JSON Decode: ' . $duration . PHP_EOL);

Apart from the exporting and importing functions used, the script for serialize() and var_export() looked pretty much the sime, var_export() being the only exception, since I had to add an ending ; to $export in order for it to work with eval().

While it is understandable that importing takes longer for every method than importing, the differences in time are quite astounding:

It's not only interesting to see that unserialize() is damn slow but also that JSON is fastest, which also gets quite clear when looking at combined results:

 

Since it's still in the Ubuntu repositories, I did the performance tests with PHP 5.2.6

Speaking at PHP Conference 2009 about Scrum

Permanent Link: Speaking at PHP Conference 2009 about Scrum 15. November 2009 Comment No Comment

Today (November, 15th) I'm giving a workshop about Scrum basics at the PHP Conference 2009 in Karlsruhe, Germany together with my colleague Sebastian Schürmann. If you're new to scrum and/or have never heard about it, it should be a quite interesting workshop for you.

Article "Mobile Webapplications" in german PHP Magazin

Permanent Link: Article 11. November 2009 Comment No Comment

As of today issue 1.2010 of the german "PHP Magazin" is available, containing my article "Mobile Webapplications" with tips & tricks for developing your own Mobile Webapplication using PHP.

As for the "OOP in JavaScript" series: I didn't forget about it, I just didn't have enough time to write the fourth part of it which will be covering scoping.

OOP in JavaScript - Part 3: Extending classes

Permanent Link: OOP in JavaScript - Part 3: Extending classes 22. September 2009 Comment No Comment

After I've already covered normal and static classes, Part 3 is about extending classes. As before, basic knowledge in OOP and JavaScript is needed.

First, let's create a class Human with setters and getters for the age:

function Human()
{

}

Human.prototype._age = 0;

Human.prototype.setAge = function(age)
{
if (typeof age != 'number') {
throw('Invalid Age provided');
}
this._age = age;
};

Human.prototype.getAge = function()
{
return this._age;
};

Since there are no keywords like class, private, public or protected in Javascript it's no surprise there's no keyword extends aswell. In order to extend a class you have to use prototyping:

function Woman(age)
{
    this.setAge(age);
}

Woman.prototype = new Human();

Now we've created a new class Woman that inherits all methods and properties from Human by assigning Woman's prototype to new Human(). To show it's easily possible, I've also changed the constructor as it now takes age as parameter. Creating a new object Woman and reading the age looks like this:

var woman = new Woman(22);
alert(woman.getAge());

You can overload methods simply by redifining them. In this case we'll overload the getAge method where we'll add an additional check and then call the parent getAge method. Since you actually don't call the parent method but call the parent method in static way, it is important to add call(this) in order to call the method in the actual context.

Woman.prototype.getAge = function()
{
if (this._age > 100) {
throw('This person is probably already dead!');
}
return Human.prototype.getAge.call(this);
};

Multiple inheritance is possible, but not very easy. For a method using Swiss Inheritance, check this page. Extending static classes might be possible, but I don't know a way. Problem is you need to clone the parent class (which is not that easy in JavaScript), if you write it like this the child becomes the parent and the other way round, meaning if you add a method in the Child it is also available in the parent:

function Cookie()
{

}

Cookie.get = function()
{
return 'something';
};

var CookieChild = Cookie;
alert(CookieChild.get());

Part 4 (probably the last one of the series for now) will cover scoping.

OOP in JavaScript - Part 2: Static classes and Singleton

Permanent Link: OOP in JavaScript - Part 2: Static classes and Singleton 15. September 2009 Comment No Comment

After I've covered normal classes in Part 1 of the series, the second part will focus on static classes and singletons. As before basic OOP and JavaScript knowledge is needed.

Generally writing and using static classes is monstly the same as normal classes. The difference is that you don't need to instantiate the object with new and you can't use prototyping nor this, since everything is in static context. One useful implementation for static classes is the Registry Design Pattern. First off we create the class with a property to store the registry values in afterwards:

function Registry()
{
}

Registry._data = {};

Right now, I can't really do a lot with this class, that's why I'll create a static method that allows me to set key-value-combinations:

Registry.set = function(key, value) {
Registry._data[key] = value;
}

Now I'm able to register stuff in the registry. Since I don't need an instance of the class I can call my method directly:

Registry.set('userIsAuthorized', false);

I'll leave out the getter you'd still need for a useful registry.

If you want to prevent anyone from writing new Registry() you only have to throw an exception in the constructor:

function Registry()
{
throw('You cannot instantiate Registry');
}

Maybe for some reason you wanna use Registry as a singleton. In that case you have to combine normal class methods and properties with static ones. You write the Registry as a normal class and implement one static property instance and one static method getInstance. The Registry class would then look like this:

function Registry()
{
}

Registry.instance = null;

Registry.getInstance = function() {
if (Registry.instance === null) {
Registry.instance = new Registry();
}
return Registry.instance;
}

Registry.prototype._data = {};

Registry.prototype.set = function(key, value) {
this._data[key] = value;
}

Since JavaScript doesn't have access modifiers like private, public or protected I had to remove the exception from the constructor. You could do it with a randomly generated token passed to the constructor, but this method is not bulletproof like any other I can think of.

In part 3 (that'll come later this week) I will write about extending classes.

OOP in JavaScript - Part 1: Writing classes

Permanent Link: OOP in JavaScript - Part 1: Writing classes 12. September 2009 Comment No Comment

OOP in JavaScript works a bit different than known from other languages. That's why I decided to do a series of "OOP in JavaScript" blogposts, where I want to show how OOP in JavaScript works. The series will discuss topics like creating classes, prototyping, extending classes, static classes, scoping, and so on. To understand these postings a basic knowledge of JavaScript and OOP is needed. This first part is about creating classes/prototyping.

First thing you need to know: There is now keyword class in JavaScript. In order to create a class in JavaScript, all you have to do is to create a function and then create a new class instance by using the known keyword new:

function Product() {}

var product = new Product();

The function we've created is the constructor of our new class. To create methods and properties there are two ways: You can either declare them in the constructor or you can do prototyping.

Declaring it in the constructor:

function Product() {
this.id = 71288;

this.getId = function() {
return this.id;
}
}

Prototyping:

function Product() {}

Product.prototype.id = 71288;

Product.prototype.getId = function() {
return this.id;
}

Personally I prefer prototyping as it is more clear. If you want to call the function getId() it always works the same way with both methods:

var product = new Product();
alert(product.getId());

This class is still quite static, since the id is hardcoded in it. To make it dynamic I just need to modify the constructor to make it accept a config object. Notice that I replaced the id property with a config property that stores the whole config given to the object.

function Product(config) {
this.parseConfig(config);
}

Product.prototype.config = {};

Product.prototype.parseConfig = function(config) {
if (typeof config != 'object') {
throw('Parameter "config" must be of type object');
}
// ID should always be set and a number
if (typeof config.id != 'number') {
throw('Config Parameter config.id must be a number');
}
this.config = config;
}

Product.prototype.getId = function() {
return this.config.id;
}

As you can see I also already implemented checks that the config must always be an object and that an id must always be set and a number. Creating a new instance of the class now looks like this:

var product = new Product({
id: 71288
});

This way we can now dynamically create Product Objects based on Product IDs we read from e.g. a database.

In the second part, that will come within the next few days I will write about static classes.

Haystack-Needle-Sheet

Permanent Link: Haystack-Needle-Sheet 4. August 2009 Comment No Comment

Surely every PHP developer has come across the PHP Haystack-Needle-Phenomenon: Mostly the parameter order is $haystack, $needle but in some cases it's $needle, $haystack for no apparent reason. Trying to find regularities I found out that it's only the array functions that use needle, haystack instead of haystack, needle - assuming I didn't forget any functions. For that reason I created a Haystack-Needle-Sheet, which shows you which function uses haystack, needle and which one needle, haystack.

If you should come across functions that are missing on this list, please let me know.

You can download the Haystack-Needle-Sheet here

< previous page | next page >