Prototype vs Class Inheritance in YUI 3

0

Posted on : 01/07/2010 | By : Jimmy Vu | In : Development News, Solution

As I mentioned in the post YUI 3.0 – Changes From the Root, YUI 3 is a radical evolvement of the framework. One of the most interesting features it provides with is about much better support for OOP.

YUI 3 supports two inheritance patterns via object prototype and “class”. Let’s examine the differences and advantages of each pattern.

Prototypal Inheritance in YUI 3

Suggested by Douglas Crockford, prototypal inheritance pattern is to deal with objects, i.e. objects inherit from objects. YUI 3 supports prototypal inheritance from its core; it means you can utilize the pattern by including the seed file only:

<script type="text/javascript" 
    src="http://yui.yahooapis.com/3.0.0/build/yui/yui-min.js"></script>

Now, for example, we have an object named animal:

var animal = {
    name: "Animal",
    level: "top",
    say: function() {
        return "I am an " + this.name + " at " + this.level + " level.";
    }
};
 
alert(animal.say()); // I am an Animal at top level.

And you want to create an elephant object that is an inheritance of animal. It’s so easy to do:

var elephant = Y.Object(animal);

Of course, you’ll need to modify the newly-born creature to make it a true elephant by overriding its parent properties and adding some new ones:

// override an animal’s property
elephant.level = "second";
 
// add elephant’s own properties
elephant.trunk = 1;
elephant.tusks = 2;

However if you want the elephant to say more about its own belongings, you’ll have to redefine say method completely.

elephant.say = function(){
    return "I am an " + this.name + " at " + this.level + " level."
        + " I have " + this.trunk + " trunk and " + this.tusks + " tusks.";
};
 
alert(elephant.say()); // I am an Animal at second level. I have 1 trunk and 2 tusks.

I think this pattern is quite easy to understand but before going forward to the next one, here are what we learn from it:

  1. We can create a new object that inherits all the properties and methods from an existing object.
  2. We can customize the new object by overwriting some/all of the members or adding new ones.
  3. The dark part is an overwritten property has no way to reference its parent’s property.

    Note: In this pattern, the child’s properties do not really overwrite its parent’s ones but they just take higher precedence. So if we delete a child’s method, the parent’s one will be back magically. For example:

    delete elephant.say;
    alert(elephant.say()); // I am an Animal at second level.

“Class” Inheritance in YUI 3

Yes, I know there are no true classes in JavaScript, however we can make constructor functions act like classes for OOP (you can read more from the book Object-Oriented JavaScript by Stoyan Stefanov).

Note: From now on, for easier to understand the pattern, I’ll call all constructor functions (that are capitalized in examples) classes; don’t be confused.

First, we’ll mimic above example by creating  Animal and Elephant classes as follows:

// parent class
function Animal(){
    this.name = "Animal";	
}
// parent’s properties
Animal.prototype.getName = function(){
    return this.name;
};
Animal.prototype.setName = function(name){
    this.name = name;
};
 
// child class
function Elephant(){}

YUI 3 supports class inheritance via oop module and because this is used widely by almost all other modules, you’ll rarely have to include it explicitly. However, for testing, just call Y.extend() method within oop’s scope (that let Elephant inherit Animal as you can guess):

YUI().use('oop', function(Y){
    Y.extend(Elephant, Animal);
 
    // test code here
    // ...
}

Next we’ll do some tests:

// create an object of Elephant
var jumbo = new Elephant();
 
alert(typeof(jumbo.name)); // undefined
alert(typeof(jumbo.getName)); // function
 
// set name for the Elephant object			
jumbo.setName("Jumbo");
alert(jumbo.getName()); // Jumbo

You can see from the example, jumbo object which is an instance of Elephant class only inherit members of the prototype, not “private” members from parent’s class and it is considered a good practice to leave all instance-specific properties as private properties and to add all the public functionality to the prototype.

Interestingly we can add some new properties with default values to child class via arguments of Y.extend(), for example, to add trunk and tusks to Elephant class:

// create an object of Elephant “class”
var jumbo = new Elephant();
 
alert(typeof(jumbo.name)); // undefined
alert(typeof(jumbo.getName)); // function
 
// set name for the elephant				
jumbo.setName("Jumbo");
alert(jumbo.getName()); // Jumbo

Last but not least, class inheritance has very powerful feature: superclass access. To see how it works, we’ll add a method to Animal class to let it say something.

// parent class
function Animal(){}
 
// parent’s method
Animal.prototype.say = function(){
    return "I am an animal.";
};

Then, we’ll overwrite say method in Elephant class, yet still be able to keep what Animal can say about.

Y.extend(Elephant, Animal, {trunk: 1, tusks: 2});
 
Elephant.prototype.say = function(){
    	  return Elephant.superclass.say() + 
		" I have " + this.trunk + " trunk and " + this.tusks + " tusks.";
};
 
// test
jumbo = new Elephant();
alert(jumbo.say()); // I am an animal. I have 1 trunk and 2 tusks.

In summary, “class” inheritance pattern in YUI 3 is more powerful than prototypal counterpart though harder to get it full, here are some important points:

  1. YUI 3 allows us to implement inheritance at (pseudo) class level in JavaScript.
  2. Inherited classes cannot directly access to parent’s own members, children only inherit prototype members by default.

    Note: Well, it is possible to inherit parent’s own properties by initializing the parent constructor from the child (but it is not always a good OOP practice). See example:

    // parent class
    function Animal(){
        this.name = "Animal";	
    }
    // child class
    function Elephant() {
        // initialize the parent using the child as "this"
        Elephant.superclass.constructor.apply(this, arguments);
    }
     
    Y.extend(Elephant, Animal);
     
    // test
    jumbo = new Elephant();
    alert(jumbo.name); // Animal
  3. You can gain access to the parent’s overridden methods via superclass.

Conclusion

Code reuse is considered as the most confusing part of JavaScript for it lacks robust OOP features that many modern programming languages provide by default. YUI 3 with the two inheritance patterns we’ve gone through is trying to fill the gap.

Prototypal inheritance is easier to understand but limit in object inheritance only. To get full OO support in YUI 3, it is advisable to study “class” inheritance pattern provided by the framework.

Why Do We Need Google Closure?

3

Posted on : 01/04/2010 | By : Jimmy Vu | In : Development News

Why Google Closure?

When a new JavaScript library arrives, a question is often raised reasonably: “Why does the world need another library?” while we’ve already had too many good ones like jQuery, Prototype, Mootools, YUI… you name it.

To find the right answer, just have a look at the package offered by Google under the name of Closure project. We’ll find there three sub-projects:

  1. Closure Compiler: a JavaScript optimizer. This is not a “yet another JavaScript compressor”, it can do more: Besides compressing your codes it can analyze your code and remove “dead” parts, correct wrong syntax, check variable references/types, warn about common pitfalls. The really good news is it comes with a Firebug extension, called Closure Inspector, that allows us to debug compressed code by linking obfuscated lines to original ones.
  2. Closure Library: a JavaScript library (as we expect) intended for use with  Closure Compiler. Basically it can do all the common tasks like other libs such as DOM manipulation, server communication, animation/effect and encloses a large set of reusable UI widgets and controls.
  3. Closure Templates: is not just a client-side JavaScript template engine like Pure but can be used in server-side with Java.

Closure Library is a big library with more than 400 JavaScript files well organized into Java-like directory structure. We’ll find there something like packages, classes/sub-classes with Java-doc syntax description (in fact, you know, there are no true packages/classes in JavaScript.)

Read the rest of this entry »

Something for Christmas: Snowfall in Picture

0

Posted on : 12/23/2009 | By : Jimmy Vu | In : Misc, jQuery

Now it is time for Christmas and if you want to add some snows to a picture like the below example, a cool jQuery plugin — created by Jason Brown — can come to help.

Read the rest of this entry »

corMVC: An jQuery-based MVC Framework

5

Posted on : 12/22/2009 | By : Jimmy Vu | In : Solution, jQuery

I know quite a few JavaScript MVC frameworks out there but corMVC is what makes me exited at most for a few reasons.

corMVC stands for “client-only-required” Model-View-Controller and that means it does not depend on specific server-side technology. In case you want to demo something, it would be perfect if everything can be done on client side. Of course, you can save changes or load data from server (via Model) as the general illustration below.

corMVC Overview

corMVC Overview

Not like other JavaScript MVC solutions, corMVC is very simple and has very small footprint. It also does not require you to build the application using scaffolding or any other command-line utilities.

Read the rest of this entry »

FireQuery – An Introduction

0

Posted on : 12/20/2009 | By : Jimmy Vu | In : jQuery

Installation

FireQuery is an extension of Firebug created by BinaryAge to help developers to keep track with jQuery expressions, data and collections as expressed on tool website:

  • Query expressions are intelligently presented in Firebug Console and DOM inspector
  • attached jQuery data are first class citizens
  • elements in jQuery collections are highlighted on hover
  • jQuerify: enables you to inject jQuery into any web page

You can install the tool from official Mozilla add-on page (it requires Firebug 1.3+ already existed.) One note: You may have to find an older version (v0.3) to make it work with current official Firebug release (v1.4) as my experience on Windows.

In Action

After installing the add-on and restarting Firefox, just go to the test page to see how FireQuery tracks embedded jQuery data on FireBug’s “HTML” tab. The image below illustrates the data embedded in accordance with the jQuery codes to inject them to the page.

Read the rest of this entry »

jQuery Code Content Assistance for Eclipse WTP

13

Posted on : 10/13/2008 | By : Jimmy Vu | In : jQuery

JavaScript code content assistance built in Eclipse WTP does very good job that I found even better than the same functionality in some commercial solutions, however, jQuery’s syntax is not supported (no surprise). That’s why jQueryWTP tool comes to help adding jQuery support to Eclipse WTP (and Eclipse PDT, MyEclipse which are based on WTP too.)

This is not an Eclipse plugin instead a tool to patch the existing plugin and inject jQuery’s syntax support into it. First download the tool from SourceForce; it’s a Java executable JAR so you can double-click to it or run it from command line:

java -jar jqueryWTP0.2forJQuery1.2.6.jar

Now browse to plugin file

org.eclipse.wst.javascript.ui_xxxxxxx.jar

and set output directory to generate the patch. Please backup the original file and set output directory different from source one.

 

jquery-eclipse-wtp-ui.gif

 

Select “Generate” button to get the patched file then copy over original file. Start Eclipse and open a HTML or script file to see jQuery’s functions listed on code assistance like image below.

Read the rest of this entry »

Zend Framework 1.6 Comes with Dojo and FirePHP Integrated

0

Posted on : 09/08/2008 | By : Jimmy Vu | In : Development News

Probably the biggest change in Zend Framework (ZF) 1.6 is about Ajax support with integration of famous Dojo JavaScript toolkit. ZF 1.6 comes with several new helpers, elements and components that help to display/interact with Dojo widgets as announced on Zend’s official site.

  • A dojo() placeholder view helper to facilitate Dojo integration in your views, including setting up the required script and style tags, dojo.require statements, and more. In essence, this supports and enhances Dojo’s modularity at the application level.
  • Zend_View helpers and Zend_Form elements and decorators that utilize Dijit, Dojo’s layout and widget platform. This simplifies creation of Zend_Form elements that can be rendered as Dijits. For instance, highly interactive widgets such as calendar choosers, time selectors, and combo-boxes are provided.
  • Zend_Dojo_Data, a component for creating dojo.data-compatible response payloads. dojo.data defines a standard storage interface; services providing data in this format can then be consumed by a variety of Dojo facilities to provide highly flexible and dynamic content for your user interfaces.
  • A JSON-RPC server component: Zend_Json_Server. JSON-RPC is a lightweight remote procedure call protocol, utilizing JSON for its serialization format; it is useful for sites that require a high volume of interaction between the user interface and server-side data stores, as it allows exposing your server-side APIs in a format directly accessible via your client. Dojo has native JSON-RPC capabilities, and Zend Framework provides a JSON-RPC implementation that is both compatible with Dojo and the published specifications.

Read the rest of this entry »

JavaScript to Detect Google Chrome

4

Posted on : 09/05/2008 | By : Jimmy Vu | In : Solution, jQuery

The negative side of having a new (and promisingly become popular) browser, no matter how good it can be, is you’ll have to test your web apps with it among many others.

Probably, the first step is to detect the browser from JavaScript code by parsing browser’s user agent, and here is what of Google Chrome.

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US)
AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13

I guess old JavaScript codes can mistakenly tell it Safari like when running the code snippet below using JQuery’s browser utility.

1
2
3
4
$.each($.browser, function(i, val) {
	 $("<div>" + i + " : <span>" + val + "</span></div>")
		.appendTo(document.body);
});

It may be no problem until you find something wrong when your apps running on Chrome only. So, here is the code line to detect Chrome generally:

1
var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );

We’ll have to change the JQuery browser utility to support Chrome detection as follows:

1
2
3
4
5
6
7
8
9
10
11
var userAgent = navigator.userAgent.toLowerCase();
 
// Figure out what browser is being used
jQuery.browser = {
	version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
	chrome: /chrome/.test( userAgent ),
	safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
	opera: /opera/.test( userAgent ),
	msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
	mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};

Now, correct result shows on test screen:

Just one notice: Current version of JQuery (1.2.6) is treating Chrome as if it was Safari and basically no serious problem has been found yet. Modifying browser detection can cause the lib render pages/elements incorrectly for it has no knowledge of Chrome’s rendering engine. To keep compatibility, you can change line 7 back to:

7
	safari: /webkit/.test( userAgent ),

Read the rest of this entry »

JavaScript in Google Chrome Not So That Fast

13

Posted on : 09/03/2008 | By : Jimmy Vu | In : Development News

How well JavaScript works is what I highly concern about Google Chrome — the browser on headlines of all tech news today.

The JavaScript engine embedded in Chrome, named V8, is developed by Google which implements ECMAScript 3 and can run standalone as stated on project website.

  • V8 is Google’s open source JavaScript engine.
  • V8 is written in C++ and is used in Google Chrome, the open source browser from Google.
  • V8 implements ECMAScript as specified in ECMA-262, 3rd edition, and runs on Windows XP and Vista, Mac OS X 10.5 (Leopard), and Linux systems that use IA-32 or ARM processors.
  • V8 can run standalone, or can be embedded into any C++ application.

Of course, we’ll have to mention the tests given out by Google itself that show JavaScript speed in Chrome  many times faster than in all other major browsers: IE, Firefox and Safari.

Google Chrome Benchmarks

Google Chrome Benchmarks

Anyway, they are tests guided by Google and I suspect that they seem be optimized toward the best of V8. So, the better way to see how good V8 perform in action is to run tests with popular JavaScript libraries like JQuery, Prototype, Dojo, Mootools, YUI which are being used in most of web applications in real world.

In a typical web application, JavaScript is mainly used for DOM selection/ manipulation rather than for heavy calculation. That’s why all libraries try to optimize DOM selection speed for (said) faster application.

To have practical view, I decided to run Mootools’ SlickSpeed tests on Google Chrome 0.2 in comparison with Firefox 3.0.1, Safari 3.1 (Windows), IE6, Opera 9.5 and especially on the nightly build of Firefox 3.1b1pre with Tracemonkey — Mozilla’s recent effort to integrate Tamarin tracing into the existing SpiderMonkey JavaScript engine — enabled and disabled. Here are the results:

Chart: Mootools SlickSpeed Test Result

Chart: Mootools SlickSpeed Test Results

SlickSpeed Benchmarks in details

SlickSpeed Benchmarks in details

(All tests were run 10 times for each browser on Windows XP SP3, AMD x64 4400+ with 2GB RAM machine)

It turns out that Google Chrome reached 6th place ahead the poor IE6 only, 49% slower than the fastest browser: Opera 9.5. Firefox 3.1 has not proved faster than the previous version in the tests, even enabling JIT engine made the results worse. (I acknowledge that it’s just pre-release beta version and Tracemonkey is not designed for optimizing DOM manipulation).

Some other conclusions we can get out from the above results (ruling out IE6 which falls far behind others in all tests) are:

Read the rest of this entry »

JQuery Site Re-redesign

0

Posted on : 08/29/2008 | By : Jimmy Vu | In : Development News, jQuery

The redesign of JQuery DOT COM site recently gained a huge amount of comments; unfortunately most of them were not positive. Developers who have come along with the library feel unhappy with new slogan “Be a Javascript Rockstar” that, said, makes them look unprofessional.

Response to a post on Ajaxian, shypht commented:

Hate to say it, but image is everything. If I was trying to sell my manager on using jQuery, Prototype, Mootools or Dojo, and sent them to those sites, I think based on look alone jQuery would be at a disadvantage. “Write less, do more” is a great slogan, “Be a Javascript Rockstar”, not so much.

Strikes me as being an amateur, and more focused on flashy effects than functionality. I love jQuery, it’s helped me loads on my most recent project, but that header just makes me cringe a bit on the inside when I see it.

While Glen Lipka described his feeling in more colorful words on his blog post:

Truthfully, I feel alienated by it.  It doesn’t resonate with me.  It makes me feel old and lame.  My hair is not long and flowing. The rockstar isn’t me.  jQuery is me.  It’s different.

Obviously John Resig & team did listen to the community and decided to kill the “JavaScript RockStar” on JQuery site.

Read the rest of this entry »