Claudiu Persoiu

Blog-ul lui Claudiu Persoiu


Archive for the ‘JavaScript’ tag

Nope PHP 6 is not here… but how about 2013?

without comments

This is a retrospective of the year that has just ended.

In case anybody is still wandering, no, PHP 6 didn’t come out and it will probably not come out any time soon.

Why is it relevant? Since I started this blog, at the end of each year I had a post related to PHP 6 and the fact that it wasn’t released. In 2008 it was a popular question, but nobody is wondering  about that anymore, and so I will close this subject now. Let’s return to the year that has just ended.

Close to the middle of the year, the version PHP 5.5 was released, bringing features like: finally , generators and many other enhancements.

Like in 5.4, these are not defining features for the language. In this new version, there are functionalities that can be easily replaced, but if present, they are welcome.

Even though PHP is proving very dynamic lately, I think this year the main keywords were HTML5 and JavaScript.

HTML5 is seeing a lot of improvements and older components begin to have more momentum. The companies are beginning to invest in games that work in the browser using WebGL. Even older games are getting ported to the platform, using technologies like asm.js.

And, because I’ve brought games into the subject, it seems very interesting to me how only 5-7 years ago the games built with JavaScript were relatively simplistic, and now they can be compared with the ones from PCs and consoles.

I think the web revolution, which many were expecting, is taking shape. Finally the Web is a platform in the true meaning and JavaScript a language truly appreciated.

The success is due to all sides, it is not only about ECMA or only about browser manufactures, now it is truly dynamic. The Web revolution is in full blow!

When it comes to backend, the spotlight was on Node.js. It is becoming an important player on the market. New frameworks have appeared  and it isn’t a platform mainly used by hackers eager to explore new technologies anymore, but also by large companies, like PayPal, LinkedIn and Yahoo, adding a vote of confidence to it. I think Node.js is finding its place and a niche in the market, and, as a JavaScript fan, I can only be happy.

An advantage of Node.js is that you don’t have to take into consideration different JavaScript versions, like in the browser. It allows the use of the latest features from ECMA freely, an environment where you can develop JavaScript with not headaches.

Technically speaking, it was a very interesting year for web development.

Finally, I want to wish you all an extraordinary 2014!

Written by Claudiu Persoiu

19 January 2014 at 11:10 PM

Posted in Diverse

Tagged with , , ,

Appcelerator Titanium – few impressions

without comments

Note: Titanium and PhoneGap are a couple of platforms for developing hybrid applications for mobile. These platforms are not written in the programming language that is native to the phone, but they can be distributed on a verity of mobile platforms.

Recently I’ve published on Github the newest and most extraordinary quizzing platform, named Just-Quizzing. I’ve build it for personal use, but because a few colleagues found it useful, I made it public.

In the initial version, for publishing the application to my Android phone, I used SL4A. I needed a way to use the application when I was on the move and didn’t have Internet access. Unfortunately it didn’t have automatic update for the quizzes. I’ve hoped that with time SL4A will have a clearer path, but the platform lost its initial momentum and I decided to write a mobile app.

I had to choose between PhoneGap and Titanium. In the past I’ve used PhoneGap because the app size was too big in Titanium, but I wanted to give it another go. In 2011, when I first wrote about Titanium, the initial app size was about 4M. Today it doesn’t seem that big, even though it isn’t small.

The perspective will be mostly about Android, even though the app was built to work also on iPhone.

I used SDK 3.1.3, without the Alloy framework.

Alloy has it’s own learning curb and I wanted to avoid it. The prupose of the application was to be a portable version for the quizzes from the server and I didn’t want to make a big time investment.

The total development time was a little more than a week.

First impression

Things don’t work as you expect them to, there isn’t a lot of flexibility. From the total allocated time, more then a quarter I was trying to do a “flyout menu”, like in applications such as: Facebook, Google Plus and Youtube. It was a total disaster! The only options that seemed to work were using an external module or using Alloy widgets.

It seems like when converting relative coordinates, where the user touched the current element, to the general coordinates on the screen there is a big discrepancy and it is impossible to do a sliding menu effect in a decent manner. In the end I totally abandoned this effect.

The speed is not that good when it comes to rendering elements. To be honest, I was expecting a better speed. There are some tricks that help, like pre-rendering the views before displaying them, but for this you must guess what the user will do next, which is not always possible.

Another thing that bothered me was that when the menu button is pressed on Android you can’t take a particular action, let’s say open the side menu that I’ve mentioned before. In PhoneGap for instance, no menu is opened, it must be built-using HTML from the ground up.

When Titanium came out, they were stating that you could develop once and distribute to multiple platforms. Now I was surprised to find that the approach had changed. In the Kitchen Sink, the application that showcases the features of the platform, each platform type initializes the application in it’s own file. One of the reasons is that the design is done dynamically if you are not using Alloy, not trough layout files.

One of the first things that I tried with Titanium was to see the size of a “Hello World” app. Packed, the application has about 8.5M, installed on the phone, it takes up about 16M. I don’t know what you think about that, but for me it is a lot! What is strange is that my final app occupies about 8.4M packed and installed about 16M, almost identical to the original application. The reason is simple, the images replaced by me are a few kb smaller, resulting in an application a little smaller than the one that I started with.

Why does a Titanium application take up so much space?

I had to do some searching before finding the answer. In 2011, when I first tried to research, I only found that all the libraries, needed or not, are packed inside and for this reason it takes up so much space. This wasn’t the cause! Meanwhile, I found the real reason. An application runs a “bridge” between Android and JavaScript. The source code is not “compiled”, as was the initial belief, but just interpreted.

The JavaScript code is interpreted using one of the available engines in the app (V8 and Rhino) and it calls other components that build the native graphing elements.

The issue is with the engines. They are quite big and are packed in every application. And, as if they weren’t large enough, there are 3 of them, each with its’ own purpose:

  • V8 – for newer Android version (after Gingerbread 2.3);
  • Rhino – for older Android versions (before Gingerbread 2.3);
  • x86 – for Intel processors.

These 3 engines occupy a total of 19M, unpacked on my computer. Thus, without eliminating some of them, we can’t get the app size to decrease.

One way Appcelerator is trying to tackle this size issue is to give up Rhino, breaking this way compatibility with older Android versions.

Community

There is a very active community. On the forums and Q/A platforms it’s full of questions and answers! I must admit that I was impressed in this aspect. Some questions are relatively old, even from 3 years ago.

Learning curb

For a week and almost a half, out of which almost a quarter I searched how to do a view moving effect, which in the end didn’t work, I must say it went pretty fast!

I must admit, I’ve played with it 3-4 years ago for a few days and I remembered a few things, like elements of type window, view and label.

The fact that I was able to find answers fast on questions about Stackoverflow, gathered in a few years, but also that the documentation is pretty well organized, helped a lot.

Also on Youtube there are some useful tutorials.

Development environment

In the first versions there wasn’t an IDE, the applications were written with an editor of choice, then packaged and tested using the platform.

Now there is an IDE based on Eclipse. The name is Titanium Studio. It has a pretty nice autocomplete, which helps in a lot of cases. It also has some drawbacks, like in my case sometimes the syntax highlight didn’t work, without any clue were the problem was. Also, project management seems a little strange and it had some issues with import and export of the projects.

There isn’t a default visual tool for editing elements in the page. Both Xcode and ADT allow for editing elements with drag & drop. It turns out there are tools for this, but they are not free.

Emulators are not very configurable. The good part is that you don’t have to worry, you select the operating system and display type and Titanium will automatically configure an emulator. The bad part is that I might wish for a clearer resource management.

Another disadvantage is that sometimes the application will crash before the emulator starts and if you try again it will try to start a new emulator without any luck, case in which the emulator has to be closed. Run Project clean and try again, careful not to miss the moment when the screen can be unlocked, or the scenario will repeat.

For iPhone logs do not work when it comes to OS X Mavericks.

Good parts

It is easy to learn.

The documentation is well done and where something is not clear, surely somebody asked the question before.

There is a fairly large community.

The IDE is easy to use.

It’s easy to see what is possible to achieve with the Kitchen Sink app.

The app doesn’t look like a web page in a WebView!

Bad parts

The app size is quite big (16M on the phone).

The graphical elements are only a subset of the platform.

It isn’t very fast, because the code is interpreted and not compiled, to be able to interact directly with the OS.

There isn’t a visual editor.

There are some issues on integration with emulators, both for Android and iPhone.

Conclusion

If you are a JavaScript connoisseur and you need an application fast and also want to have native graphical elements, then probably Titanium is for you.

If you want performance, probably you need to look for something else.

I don’t have enough experience with the Android SDK to be able to build this application in the timeframe I had available, this was my compromise.

To be honest, I’m not sure wether PhoneGap was a better option or not, speaking for my case. Today there are a lot of JavaScript libraries out there built especially to emulate native graphical elements into a PhoneGap application. The difference is not necessarily visible and, in the end, maybe sometimes the app doesn’t really have to look like a standard app, maybe a completely different interface is more appropriate.

Written by Claudiu Persoiu

24 December 2013 at 1:13 PM

Posted in JavaScript

Tagged with , ,

Closures, from Scheme to Javascript to PHP

without comments

The notion of closure in PHP, even though it appeared in PHP 5.3, as I’ve said before on my blog, it was properly done only in 5.4.

Wikipedia tells us:

In computer science, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables) of that function.

In PHP this isn’t a very popular concept or very well-known. It is often mistaken for Anonymous Functions. But in functional programming languages it is very popular, because they really need it!

Scheme

When Brendan Eich designed JavaScript, relied on the Scheme language and ended up doing an implementation of this language with a C syntax. The C syntax was and is a lot more popular, and back then (1995) the Java programming language was very “fashionable”.

The Scheme syntax is similar to Lisp, in the sens that is using parenthesis abound expressions in order to execute them. The operators are defined as functions and just like them, there must be placed left of the parenthesis.

Let’s take an Scheme closure example:

(define (make-counter)
  (let ((count (begin 
                 (display "run parent function and return 0") 
                 0)))
    (lambda ()
      (set! count (+ count 1))
      (begin 
        (display "inside child function ") 
        count))))

The function is setting a “count” variable, with the value 0 and displays “run parent function and return 0”, then returns another lambda function, that is incrementing the variable defined in the main function and then displays “inside child function”.

I’m storing the resulting function in a variable in order to later run it multiple times:

> (define counter (make-counter))
run parent function and return 0
> (counter)
inside child function 1
> (counter)
inside child function 2

In other words, each time I’m calling (make-counter), it will return a new function that has access to the environment at the time at which it was created. If it looks strange because of the syntax, I promise that it will fell a lot more natural in JavaScript.

This concept is very interesting for encapsulation. The environment from the time when the parent function was been executed can be encapsulated, and later it can be used without worrying that it was changed by external causes.

For the functional programming languages this is a very interesting concept. Yet when it comes to object orientated languages, the concept seems almost useless, because objects also have the purpose of encapsulation.

JavaScript

From the beginning JavaScript was a hybrid, a functional programming language, object orientated, with prototype based inheritance. And if this wasn’t enough, the syntax was taken from Java (C).

JavaScript didn’t inherited a lot from Scheme, but it did inherit the closure concept.

A reason why there was a need for closures in Scheme is that that if a function is not finding a variable in its environment, it will search for it in its container’s environment. Let’s take an example:

(define x 1)
(define (add-in-env y) (+ x y))

If we call add-in-env with 2:

(add-in-env 2) -> 3

It looks just as ambiguous as in JavaScript, but is not exactly like that. In Scheme to do mutation is not that easy, simple and transparent, so an subsequent operation of:

(define x 2)

will result in an error.

In JavaScript resulted a hybrid. Mutation is permitted, but the notion of searching a variable in the current environment remained:

var x = 1;
var add_in_env = function (y) {
   return x + y;
}

add_in_env(2); // returns 3

Up to this point is ok, but for:

x = 2;
add_in_env(2); // returns 4

For this case, things can get out of hand very easy:

But, in order to solve the issue, we can just define a variable in the environment that will finish execution (will close):

var make_counter = function () {
   console.log("run parent function and set counter to 0")
   var count = 0;

   return function () {
       count = count + 1;
       console.log("inside child function");
       return count;
   }
}

var counter = make_counter();
console.log(counter());
console.log(counter());

var counter2 = make_counter();
console.log(counter2());
console.log(counter());
console.log(counter2());

The output will be:

run parent function and set counter to 0
inside child function
1
inside child function
2
run parent function and set counter to 0
inside child function
1
inside child function
3
inside child function
2

Even though the main function finished executing, the environment inside it is kept as a closure for the function that was returned. Only when there aren’t any more references to the sub-function the memory allocated for the closure will also be deallocated.

Even though JavaScript has objects, it doesn’t have private methods. An approach is to add a “_” (underscore) in front of the function name and consider it private. From my point is like asking the developers that will later use the code to consider this function private. Of course this is not very consistent.

Let’s take an example:

var obj = {
   _secretFunction : function (key) { console.log(‘do secret ’ + key) },
   doStuff : function (key) { this._secretFunction(key) }
}

obj.doStuff(‘stuff’); // do secret stuff

It seems that there is a public method “doStuff” and a private one “_secretFunction”. Nevertheless you can not prevent a user from calling “_secretFunction” or even worse, to modify it:

obj._secretFunction = function (key) { console.log('new secret ' + key); }

obj.doStuff('stuff'); // new secret stuff

If we want to hide the function, and make this obvious for everybody, again, we can use closures:

var obj = (function () {
   var secretFunction =  function (key) { console.log(‘do secret ’ + key) }

   return {
      doStuff : function (key) { 
         secretFunction(key) 
      }
   }
})();

obj.doStuff(‘stuff’); // do secret stuff

Because the parent function was not stored but rather immediately executed, basically the space in which secretFunction was defined has already finished its execution, encapsulating the logic. The object returned can call the function because it was defined in the same environment as the object.

Looks complicated at first, but is really very easy when you understand the concept.

And then it was… PHP

PHP includes a lot of different options. It was originally developed as a Perl framework, later the engine was rewritten in C.

PHP is a dynamic language that includes a lot of concepts, from objects, interfaces and anonymous functions, up to goto labels. The development direction for the language is not very clear, it rather offers the possibility for different approaches.

In the weird PHP history, somewhere in version 4, syntax for Anonymous Functions was added, but only in PHP 5.3 a more “normal” version appeared.

Also in version 5.3 the first closure version was introduced:

$scalar = 5;

$closure = function () use ($scalar) {
     return 'Scalar: ' . $scalar . PHP_EOL;
};

echo $closure(); // Scalar: 5

$scalar = 7;

echo $closure(); // Scalar: 5

This version mostly worked, but you had to specify what you want to send to the closure.

And there were other inconveniences:

<?php 
class Foo {         
   private function privateMethod() {                 
      return 'Inside private method';         
   }

   public function bar() {                 
      $obj = $this;                 
      return function () use ($obj) {                         
         return $obj->privateMethod();
      };
   }
}

$obj = new Foo();
$closure = $obj->bar();
echo $closure();

Fatal error:  Call to private method Foo::privateMethod() from context '' in [...][...] on line 10

Is not working because you can not send $this as a parameter to a closure, and if you try the above trick you still can’t access the private methods. Remember, this was happening in PHP 5.3.

The idea to introduce a closure of this kind seems strange to me. But this is not the first time something “strange” is introduced in PHP, as I was saying before about the Anonymous Functions. Sometimes is looking like work in progress.

I think everybody was expecting a more JavaScript like closures. I think that JavaScript had a big influence in making this concept so popular.

In version PHP 5.4 things changed, we finally have a closure as we would expect:

class Foo {
   private function privateMethod() {
      return 'Inside private method';
   }

   public function bar() {
      return function () {
         return $this->privateMethod();
      };
   }
}

$obj = new Foo();
$closure = $obj->bar();
echo $closure(); // Inside private method

And it works!

You can even do:

unset($obj);
echo $closure();

and it will work, because the object in which the closure was defined remains in memory until either the script finishes execution, or a call like this is made:

unset($closure);

For more details on how closures work in PHP 5.4, check out this post.

Written by Claudiu Persoiu

10 April 2013 at 10:02 AM

A new JavaScript game – Minesweeper

without comments

It’s time to publish another JavaScript game, this time is Minesweeper.

The first version of the game was made about an year and a half ago, but meanwhile I’ve completely rewritten it because of performance issues.

I believe this will be the last game that I didn’t make using canvas for compatibility reasons.

Unlike the other games that were made literally over the week-end (the exception was Puzzle Gd) this game proved to be a little more complicated.

For the design I must thank (again) to Cătălinei Radu.

Enjoy!

Written by Claudiu Persoiu

16 October 2011 at 9:47 AM

Posted in Diverse,JavaScript

Tagged with , ,

PhoneGap – first impressions

without comments

Last week I wanted to make an mobile application (Android). Initially I wanted to use Titanium, a platform that I’ve played with in the past and I was nicely impressed.

But after I downloaded the compiler and made the first application I had a surprise, the “Hello world” app had about 5M. How did it get so big? Simple, Titanium compiles the application into native code but there is no clear method by which to determine what APIs are used, so the minimum necessary APIs are compiled in order for all features to work. The perspective of an app bigger then 5M didn’t impress me, so I’ve started searching for alternatives.

I’ve installed Phonegap, I wanted to make a game on this platform for a long time, but because the installation is not as elegant as it is for Titanium I wasn’t very delighted. I’ve made a “Hello world” app and it had only… ~200k! A reasonable size in my opinion.

Of course there is a reason for that size, PhoneGap is giving access to a lot of features like: accelerometer, camera or contacts, but nothing on the presentation layer. The presentation is made exclusively with HTML, CSS and JavaScript.

The entire PhoneGap project is based on the fact that most platforms have a “web view” that can parse a web page.

But because the project is not as “packed” as Titanium new features can be added relatively easy. For instance, for Android there are a decent number of projects that add new features to the platform. Loading them is not very difficult, but is not plug & play. Basically there are Java modules for Android that expose an API that can be called from “web view”. This can be an advantage, because there is a community that is developing features that don’t necessarily need to be in the “core”.

For simple apps that only list or display information, the platform is a interesting alternative, especially because there are a lot of JavaScript and CSS frameworks for formatting mobile pages like: jQTouch, jQuery Mobile or XUI. The platform is great for packing applications of this nature. For instance if you have an HTML app for mobile and you want to add some native phone features and to distribute the compiled version, PhoneGap does a great job.

On the other hand, even if you can access for instance the menu button, you can’t create a native menu.

As a conclusion, this is a platform that has a completely different approach to Titanium. If Titanium is based on the fact that an application will compile to native code with native APIs, all the code base is written in JavaScript and web view is only one of the options available, PhoneGap’s approach is that the presentation is made exclusively in a web view using HTML(5) + CSS and only some device specific APIs can’t be accessed from the browser and are not presentation related to be exposed, like: vibration, buttons, etc. Taking that into consideration I don’t think that the two platforms can be really compared, only the developer can decide what approach is best.

Written by Claudiu Persoiu

14 August 2011 at 3:05 PM

Posted in Diverse,JavaScript

Tagged with , ,

Android calculator vs. JavaScript

with 2 comments

Is about the phone’s calculator. I have a HTC Desire with Android 2.2. My default calculator app that’s called simply “Calc” amazes me. Very rarely happens to need to use it, end even less I’m using it with fractional numbers, but when I’m actually using it I tend to forget that it has an issue.

Let’s say:

12 – 11

In Calc = 1, in JavaScript = 1. Nothing out of the ordinary so far, right?

Let’s take:

1.2 – 1.1

Any elementary school student knows that the result is 0.1.

In Calc it is 0.099999999, weird? In JavaScript is even more interesting, the result is 0.09999999999999987.

It’s about float, and I assume that the difference comes from the digit number displayed on the screen. In both cases IEEE 754 standard is used.

Now… in JavaScript this is a known issue, but who made the Android app, made it transform to a scientific calculator if you rotate the phone and did not see this issue?

Written by Claudiu Persoiu

3 May 2011 at 10:19 PM

Posted in Diverse

Tagged with ,

Closures and lambda functions in PHP vs. JavaScript

with 2 comments

JavaScript and PHP support both lambda functions and closures. But the terms are poorly understood in both programming languages ​​and are often confused with each other.

Lambda functions

Also called anonymous functions. They refer to functions that can be called without being bound to an identifier. One of their purposes is to be passed as arguments. The Lambda name was introduced by Alonzo Church, inventor of lambda calculus in 1936. In lambda calculus all functions are anonymous.

JavaScript

In JavaScript lambdas are part of the standard set and there are the preferred method of defining functions.

For instance:

var add = function (a, b) {
     return a + b;
}
alert(add(1, 2)); // 3

Lambda functions are used almost in any context when it comes to JavaScript, like:

window.onload = function (e) {
     alert('The page has loaded!');
}

PHP

In PHP, lambda functions were introduced in version 4.0.1 using create_function. In version 5.3+ a similar syntax to JavaScript was added, a much more readable and elegant way of defining a function.

This means that in PHP there are two ways of creating a lambda function:

// PHP 4.0.1+
$add = create_function('$a, $b', 'return $a + $b;');

// vs.

// PHP 5.3+
$add = function ($a, $b) {
     return $a + $b;
};

echo $a(1,2); // 3

Lambda functions can be used as parameter for other functions, such as usort:

$array = array(4, 3, 5, 1, 2);
usort($array, function ($a, $b) {
     if ($a == $b) {
          return 0;
     }
     return ($a < $b) ? -1 : 1;
});

Even more, PHP 5.3+ allows calling an object as a anonymous function:

class test {
     function __invoke($a) {
          echo $a;
     }
}
$a = new test();
$a('test'); // 'test'

Closures

The closure is really the misunderstood concept of the two. In general confusion appears because closures may involve lambda functions. A closure refers to the ability of a function/object to access the scope in which it was created even if the parent function has ended it’s execution and returned. In other words, the function/object returned by a closure is running in the scope in which it was defined.

In JavaScript the notion of closure is part of the standard arsenal, because the language is not based on the traditional object model, but rather on prototypes and functions. But JavaScript has some traditional object model parts, like the fact that you can use “new” to construct an object based on a function that plays the role of a class. In PHP closures are more of an new way to approach problems, because PHP is part of the traditional object model family.

JavaScript

In JavaScript the notion of closure is widely used, it’s so popular because JavaScript is not a traditional object orientated language, but rather a functional one, based on prototype inheritance.

JavaScript doesn’t have Public, Private and Protected, but rather only Public and Private and objects an inherit from each other, without using classes.

Another issue is the scope, because the global scope is used by default. This issues can be fixed in an elegant fashion using closures:

var closure = function () {
     var sum = 0;
     return {
          add: function (nr) {
               sum += nr;
          },
          getSum: function () {
               return sum;
          }
     }
}();

closure.add(1);
closure.add(2);
console.log(closure.getSum());

In the example above, sum is a private property and in theory can only be accessed and modified by the closure function. The interesting part is that the parentheses from the end of the function definition, signify that this function will be immediately  executed and therefore will return the result which is an object. At this point the original function will only exist for serving the return object, encapsulating therefor the private variable.

Although the function has finished execution, through this closure the returned object can still access the variables defined in the function scope, because that was the environment in which it was created.

This becomes even more interesting when a function returns another function:

var counter = function () {
    var counter = 0;
    console.log('in closure');
    return function () {
        console.log('in the anonymous function');
        return ++counter;
    };
};
var counter1 = counter();

console.log(counter1()); // 1

var counter2 = counter();
console.log(counter2()); // 1
console.log(counter1()); // 2

The output will be:

in closure
in the anonymous function
1
in closure
in the anonymous function
1
in the anonymous function
2

What actually happens is that the first function is executed and returns an anonymous function that can still access the environment in which it was created. In my opinion this is where the confusion between closures and lambda functions comes from, because a function returns another function.

The difference between examples is that in the first one the closure function executes immediately, and in the second example when counter is executed it’s returning a result that is actually a function definition, which in turn can be executed. Of course the second example can be modified to act just like in the first example using parenthesis.

PHP

As I said above, the notion of closure in PHP is not as important as in JavaScript.

Considering that lambda functions are available in the language since version 4, closures only appeared with PHP 5.3+.

Because of the block scope nature of PHP, there is a better encapsulation but there is a lot less flexibility compared to JavaScript. Basically in PHP you must specify using the use instruction what will the anonymous function be able to access from the closure scope.

function closure () {
     $c = 0;
     return function ($a) use (&$c) {
          $c += $a;
          echo $a . ', ' . $c . PHP_EOL;
     };
}

$closure = closure();

$closure(1);
$closure(2);

Unlike JavaScript, in PHP closures can not return objects, or rather the object can not be bound to the scope in which it was created, unless you send the variables as a reference to the constructor, in which case is not very elegant and I can’t imagine a scenario that would absolutely need closure for this.

Like in the JavaScript examples, instead of parentheses “()” at the end of the function, in PHP to run a function immediately after defining it call_user_func() or call_user_func_array() can be used:

$closure = call_user_func(function () {
    $c = 0;
    return function ($a) use (&$c) {
        $c += $a;
        echo $a . ', ' . $c . PHP_EOL;

    };
});

$closure(1);
$closure(2);

Written by Claudiu Persoiu

16 April 2011 at 6:02 PM

The story of JavaScript told by Douglas Crockford la Yahoo!

without comments

Douglas Crockford on JavaScript

As I am a big fan of Douglas Crockford, the inventor of JSON, several weeks back I’ve found a new series of presentations. The presentations took place in 2010 and can be found on the YUI blog dedicated page: http://yuiblog.com/crockford/.

Why am I a Crockford fan? There were 3 thinks that surprised me on his first presentation I’ve seen:

  • he argued fiercely that JavaScript has good parts, but they are not understood,
  • said that JavaScript is a functional language, and as such should be taken in order to discover its beauty,
  • he was one of the few to write a true programming book for JavaScript and not just a collection of special effects like the majority did at the time.

The series “Crockford on JavaScript” at Yahoo!, is not exactly new but very topical.

What is different about this presentations is that there not completely focused on syntax, language and “good parts”, but rather on the overview picture, all the story of the language, including the storys of the languages that influenced it.

The presentations are quite long, over an hour each, but very interesting in my opinion, especially if you’re a fan of computer history.

Part Three can be a bit more difficult because there are some notions that may seem quite bizarre. But once you get familiar with them, many other things become more clear.

Written by Claudiu Persoiu

9 April 2011 at 2:55 PM

Posted in JavaScript

Tagged with ,

The 3d web with HTML5

without comments

Last week-end I was surfing the Web wandering why there isn’t any 3d done in JavaScript. A ridiculous question in a hot afternoon.

My question was born from the idea that the first stage in 3d evolution was done in 2d, basically representing 3d objects using the existing 2d ways.

Of course I came across my first answer: a 3d shooter game directly in the browser, done by Ben Joffe!

It is at least impressive!

Beside this find I immediately came across some other 3d games in JavaScript that are not using tags like canvas, but this results are not very impressive because of a simple reason: speed!

Before HTML5 the speed of displaying elements in the browser was a very big issue. Is well know that one of the slowest components of the browser is the DOM, especially in Internet Explorer. When it comes to the canvas a huge difference is visible in the good way, the multitude of the objects on the stage are not coordinated using the DOM but rather just displayed in a true graphical element.

While I was opening my computer today I was thinking why doesn’t anyone make a game at least like Duke Nukem 3D? Of course the browser will not become just yet a platform that can compete with XBOX for games ant that’s normal… I don’t even know how did I come across this, but it was just like something in my universe drown me to something truly impressive:

Quake 2 directly in the browser, using JavaScript!

At the beginning I thought that they cheated, they’ve used WebGL, not just the 2d popular canvas. But the result is truly impressive, and this standard will probably be available as an HTML5 specification, which means it will be available on at least a part of the browsers.

Even though they’ve used GWT, the resulting code is still JavaScript, so this can be made just using JavaScript!

Where did the hole idea of 3d in browsers came from? I’ve read about 2 years ago about some efforts in this direction, and they ware based on VRML. But VRML exists as a standard since 1994 and I haven’t seen anything  impressive yet. I even have a VRML book that is full of dust in a shelf. The biggest issue was that there was no native support for it.

The new perspective is absolutely innovative, because is a bridge between the browser and the 3d hardware. So if one day we will have 3d in our browsers it will be done this way!

Written by Claudiu Persoiu

8 June 2010 at 10:35 PM

Posted in Browsers,JavaScript

Tagged with , ,

Unknown runtime error – Internet Explorer with InnerHTML – another meaningful error

without comments

I was working the other day on a new JavaScript game for the games section. Like the majority of the developers (like the statistics show) I’m using FireFox for developing. But as the game reached the testing faze it was time to see if it was working properly in Internet Explorer.

To test in Internet Explorer is a real pleasure, basically you see an error and then you hope that you’ll find the source.

Of course there was an error, one full of meaning as usual:

Unknown runtime error??? WTF??? If he does not know how should I?

The piece of code that was generating the error was:

canvas.innerHTML = '';

Where canvas was a variable which was storing an document.getElementById(‘canvas’), and the id canvas was from:

<table border="0" cellspacing="0" cellpadding="0">
<tbody id="canvas"></tbody>
</table>

Looks wrong? well is not because at that point I was testing other games which are using the same thing with no trouble, even in IE.

I’ve tried it in IE 6, of course with the same result.

It looks like this error appears on elements like table, tbody, p and others.

To finally fix the issue I used instead of a tbody, a div tag in which I’m adding the elements and the issue was gone.

What is interesting is that this issue does not always appear for a specific tag!

Thank you Microsoft for this meaningful error messages that are so full of logic!

Written by Claudiu Persoiu

6 June 2010 at 2:20 PM