Search Logger
Posts from: Stoyan Stefanov

Author Archive

Inheritance Patterns in YUI 3

9:30 am - January 6, 2010 in Yahoo! User Interface Blog

Stoyan Stefanov.About the Author: Stoyan Stefanov (@stoyanstefanov) is a front-end engineer at Yahoo! Search. He is also the architect of YSlow 2.0, co-creator of the smush.it image optimizer, speaker and technical writer. His latest book is called Object-Oriented JavaScript.

This article discusses two JavaScript code reuse patters implemented in YUI 3 – the classical inheritance pattern and the prototypal inheritance pattern.

Satisfying dependencies

The prototypal pattern is available from the core YUI 3 API in the yui-min.js seed file. The classical pattern requires the oop module, but since the oop module is a requirement for most of the other modules, you usually won’t have to do anything special to get access to this functionality. But if you want to create a simple test page to play with the patterns yourself, you can satisfy the dependencies by including YUI like so:

<script type="text/javascript" src="http://yui.yahooapis.com/3.0.0/build/yui/yui-min.js"></script>
<script>
YUI().use('oop', function(Y){
  // your code goes here
  // Y is the YUI instance
});
</script>

(pseudo)Classical inheritance

You can call this pattern “classical” not because it comes from Plato’s ancient Greece, but because it helps you think in terms of classes. JavaScript doesn’t have classes (hence the “pseudo” part), but it has constructor functions instead.

In Java or other languages you can have a Programmer class inherit from a Person class. In JavaScript, you’ll actually have a Programmer constructor function and a Person constructor function. The goal is to have objects created with the Programmer constructor inherit properties and methods as if they were created with the Person constructor.

Consider these two constructors:

// parent
function Person() {
  // "own" members
  this.name = "Adam";
}

// properties of the parent's prototype
Person.prototype.getName = function() {
  return this.name;
};

// child constructor
function Programmer(){}

YUI 3’s oop module offers the Y.extend(...) method to help you with the inheritance part. It’s as simple as:

Y.extend(Programmer, Person);

Then you can test that the getName() method was properly inherited:

var guru = new Programmer();
alert(typeof guru.getName); // "function"

Note that the Y.extend(...) method will only inherit members of the prototype, not “own” members. It is considered a good practice to add all the reusable functionality to the prototype and leave all instance-specific properties as own properties (added to this). In the example above, only getName() gets inherited, while name does not. (In the prototypal inheritance pattern – discussed further in the article – you inherit both prototype and own members.)

Extend and augment

Y.extend(...) allows you to inherit from a parent constructor and at the same time augment the child with new members. This is actually the de facto pattern used by YUI to build “class” extensions.

You can add properties to the prototype of the child constructor using the third parameter to Y.extend(...) and you can add properties to the constructor itself (class static properties) using the fourth parameter.

Here’s an example of extending and augmenting at the same time:

Y.extend(Programmer, Person, {groksHTML: true}, {LIMIT: "sky"});

// groksHTML is now a property of the child's prototype
alert(typeof Programmer.prototype.groksHTML); // "boolean"

// the property works for all new objects
var bob = new Programmer();
alert(bob.groksHTML); // true

// adding to the constructor is more for
// "static" properties meant to act as constants
alert(Programmer.LIMIT); // "sky"
var limit = bob.LIMIT; // undefined

Superclass

The pseudoclassical pattern described above gives you access to the prototype of the parent’s constructor via the static property called superclass.

superclass points to the prototype of the parent and so superclass.constructor points to the parent constructor function. Consider an example:

// inherit
Y.extend(Programmer, Person);

// child's access to the parent constructor
var parent = Programmer.superclass.constructor;
// test
alert(parent === Person); // true

// access to the parent from an instance of the child
var guru = new Programmer();
guru.constructor.superclass.constructor === Person; // true

As noted earlier, with the classical pattern you only inherit prototype members. But using the superclass you can also initialize the parent constructor from the child and get the parent’s own properties as the child’s own properties.

You can modify the Programmer constructor to call the parent constructor, passing the child object (this) and any initialization arguments

// ... parent definition same as shown before...

// child
function Programmer() {
  // initialize the parent using the child as "this"
  Programmer.superclass.constructor.apply(this, arguments);
}

// inheritance
Y.extend(Programmer, Person);

// test
var pro = new Programmer();
alert(pro.name); // "Adam"

As you can see, the programmer instances now have a name property and it’s an own property.

  alert(pro.hasOwnProperty('name')); // true
  alert(pro.hasOwnProperty('getName')); // false

Access to overridden methods

The fact that superclass points to the prototype of the parent lets the child gain access to overridden methods. Consider this classic example of Triangle that inherits Shape:

// parent
function Shape(){}
Shape.prototype.toString = function() {
  return "shape";
};

// child
function Triangle(){}

// inheritance
Y.extend(Triangle, Shape);

// child overrides the parent's toString() method
// but thanks to the superclass property
// it still has access to the original method
Triangle.prototype.toString = function(){
  return Triangle.superclass.toString() + ", triangle";
};

// test
var acute = new Triangle();
acute.toString(); "shape, triangle"

Prototypal inheritance

Douglas Crockford suggests this inheritance pattern, where you forget all about classes and have your objects inherit from other objects. For example:

// parent object, created with a simple object literal
var parent = {
  name: "John",
  family: "Wayne",
  say: function() {
    return "I am " + this.name + " " + this.family;
  }
};

// the inheritance magic
// a new object is born from an existing one
var batman = Y.Object(parent);

// customize or augment the new object
batman.name = "Bruce";

// use
batman.say(); // I am Bruce Wayne

Using this pattern there are two steps in setting up your objects:

  1. You create a new object inheriting all the properties and methods from an existing object.
  2. You customize the new object – you can overwrite some of the members or add brand new ones.

Note that Y.Object(...) is available in the YUI core. You don’t need to include the oop module.

Prototypal inheritance discussion

If you’re curious about the motivation behind the prototypal inheritance and how it works under the hood, you can study the pattern described in Douglas Crockford’s own words.

Using this pattern, the parent’s members are inherited via the prototype chain. That means that if you add a property with the same name to the child, the new property will not overwrite the one inherited from the parent, but it will take precedence. In other words, you can redefine the say method like so:

batman.say = function() {
  return "Can't tell you my real name";
};

// test
batman.say(); // "Can't tell you my real name"

Unlike in the classical inheritance model afforded by Y.extend, there is no way to reference the parent’s say method from the child object’s say (vis. superclass). However, if you delete the say method of the child object, the parent’s say will “shine through”.

delete batman.say;
batman.say(); // "I am Bruce Wayne"

In ECMAScript 5

The new edition of the ECMAScript standard includes the prototypal inheritance pattern through a native method called Object.create(...).

// YUI3
var batman = Y.Object(parent);

// ECMAScript 5 (future)
var batman = Object.create(parent);

More?

Thanks very much for reading! For more information and examples of the two patterns discussed in this article, you can consult these links:

Stay tuned for a follow-up article that discusses even more code reuse patterns in YUI3.

 

More code reuse patterns in YUI3

9:41 am - January 7, 2010 in Yahoo! User Interface Blog

Stoyan Stefanov.About the Author: Stoyan Stefanov (@stoyanstefanov) is a front-end engineer at Yahoo! Search. He is also the architect of YSlow 2.0, co-creator of the smush.it image optimizer, speaker and technical writer. His latest book is called Object-Oriented JavaScript.

This post is a follow-up to the article “Inheritance patterns in YUI3″ and dives deeper into the YUI3 APIs showing more patterns for code reuse. The Gang of Four book advocates that we should “prefer object composition to class inheritance”. And in fact, inheritance is sometimes used as a workaround in strongly typed languages where the signature of an object or a class needs to be fixed at compile time. JavaScript is loosely typed and objects can be composed, mixed and augmented at any time.

Augmenting objects

In real-life JavaScript, it’s rare that you would have to setup deep inheritance chains. Often you may only want to augment an existing object (or a constructor) with the members of another, without necessarily forming a parent-child relationship. YUI offers the method Y.augment(...) to do just that.

The following example illustrates the difference between the proper inheritance with Y.extend(...) and the simple object augmentation with Y.augment(...).

// parent, a.k.a. supplier of functionality
function Programmer(){}
Programmer.prototype.writeCode = function(){};

// a constructor that gets augmented with supplier's members
function CodeMonkey(){}
Y.augment(CodeMonkey, Programmer);
var monkey = new CodeMonkey();

// a constructor that inherits from the parent-supplier
function Guru(){}
Y.extend(Guru, Programmer);
var guru = new Guru();

Now that we’ve reused Programmer’s functionality in two ways, let’s test the outcome. Both objects monkey and guru now get a writeCode() method, but only the guru is part of the inheritance chain.

alert(typeof monkey.writeCode); // "function"
alert(typeof guru.writeCode); // "function"

// monkey is not a Programmer, while guru is
alert(monkey instanceof Programmer); // false
alert(guru instanceof Programmer); // true

Y.augment(...) can also take an object (as opposed to a constructor) to be augmented.

var n00b = {};
Y.augment(n00b, Programmer);

// now n00b can writeCode
alert(typeof n00b.writeCode); // "function"

Y.augment(...) allows the recipient to be more picky when reusing code from the supplier. An optional third parameter to Y.augment(...) defines whether existing properties should be overwritten (false by default, meaning preserve the original properties of the recipient). The fourth parameter can optionally provide a whitelist – an array containing the names of the properties that should be carried over.

Cloning

Cloning objects is yet another pattern for code reuse, which allows you to create brand new objects which are just like existing ones. In a way, the idea is similar to the prototypal inheritance (see Y.Object(...) in the previous article), where objects inherit from objects. The main difference is that when cloning, the parent’s properties get copied to the child directly, not through the prototype chain.

Y.clone(...) creates a deep copy, meaning it recurses through array and object properties. It also creates copies by value, so that the cloned object doesn’t modify the parent by mistake (in JavaScript arrays, objects and functions are copied by reference).

To illustrate the difference, consider an object pro that gets cloned into a new object clone and also inherited as wiz using Y.Object(...).

// original object
var pro = {groks: ['html']};

// inherit
var wiz = Y.Object(pro);

// clone
var clone = Y.clone(pro);

Now let’s add a new array element to the original object

pro.groks.push('css');

The child object sees the updated value, while the clone doesn’t, because the clone is a snapshot of what the object was at the time of cloning.

wiz.groks.join(); // "html,css"
clone.groks.join(); //"html"

This works the other way around as well – when the child modifies the array.

wiz.groks.push('js');
pro.groks.join(); // "html,css,js"
clone.groks.join(); // "html"

Clone discussion

As you can see Y.clone(...) creates new objects by deep-copying all their properties and methods. Although this is probably not what you’d normally call inheritance, it’s still a pretty simple and straightforward pattern for code reuse. After all code reuse is about avoiding the need to duplicate code and reusing existing functionality.

Something you may be wondering – what about performance? Isn’t it inefficient to copy values like that. The answer is – yes, it could be inefficient. But for most applications this would rarely be the bottleneck. In fact Firebug (Firefox extensions are written in JavaScript), which is a pretty complex piece of software has an extend() method which works by simply copying properties from the parent object to the child object, using a shallow copy (not recursing into objects and arrays).

So, since cloning is just deep-copying properties from one object to another, wouldn’t it be nice if you can inherit functionality from multiple objects, not only from one? This is where Y.merge(...) comes to help you with this sort of mix-in objects.

Mixin objects with Y.merge(...)

The mixin pattern allows you to grab properties and methods from multiple objects and carry them over into a new object. YUI3 provides the method Y.merge(...) which can take any number of objects and return a single one which is a mix of all source objects.

Here’s an example:

var mad_skillz = {bake: function(){}, mix: function(){}, eat: function(){}};
var ingredients = {sugar: "lots", flour: 1, eggs: 2};
var dairy = {milk: 1};

// mixin
var cake = Y.merge(mad_skillz, ingredients, dairy);

Now you can test which properties got carried over to the cake object using the convenient method Y.Object.keys(...) which gives you an array of all property names.

Y.Object.keys(cake).join(); // "bake,mix,eat,sugar,flour,eggs,milk"

Y.merge(...) resembles cloning, but instead of deep-copying one object, it creates a shallow copy and can take multiple objects to mix with the same method call. The overwriting logic of Y.merge(...) in cases of property naming collisions is different than most other methods – if you have two members with the same name, the last one wins and overwrites the previous.

Just like with Y.clone(...), Y.merge(...) is not necessarily limited to the purposes of code reuse. You can use them also for manipulating arrays or any sort of hash-like objects, such as configuration objects.

Y.mix(...)

Y.mix(...) is the lower-level method behind most of the functionality discussed above. It offers you a fine-grained control over which properties get copied and where exactly. It also allows you to combine two properties with the same names, ignore certain properties and so on.

Here’s a somewhat complex example of using the Y.mix(...) API:

// an object
var pro = {
  groks: ['html', 'css', 'js'],
  speaks: ['Latin'],
  tweets: true
};

// a constructor
function WebGuru(){}

// augmenting the prototype of the constructor
// with some of pro's properties
Y.mix(WebGuru, pro, true, ['groks', 'tweets'], 4);

// test
var guru = new WebGuru();
guru.groks.join(); // "html,css,js"
guru.tweets; // true
guru.speeks; // undefined

If you look at the call to Y.mix(...), we have 5 arguments, meaning:

  1. WebGuru gets more members…
  2. from pro
  3. overwriting any existing ones…
  4. only if they are in this whitelist array ['groks', 'tweets']. This means that the speaks property will not be mixed
  5. 4 is the mode. There are five mixing modes – 0 to 4, where 4 means that the prototype of WebGuru will receive members from pro.

You can check the docs for more information on the parameters accepted by Y.mix(...).

That’s all folks!

Thank you for reading! For more information and examples on the OOP functionality in YUI3, you can consult these links:

 

‘Tis the season for developers’ calendars

3:04 pm - December 3, 2010 in YDN Blog

Christmas is upon us. Developers are embracing the spirit of sharing their knowledge and wisdom, while taking the opportunity to look back and recollect what 2010 brought us in terms of new technologies and ideas.

A number of "advent" calendars started posting their blog-a-day-till-Dec-24th. Here are some for your reading pleasure while you kick back with a glass of wine by the fireplace:


24 Ways Advent Calendar 24 ways (to impress your friends) started back in 2005. It focuses on web design, as well as development topics.


PHP Advent Calendar PHP advent is the same but for PHP-related topics (psst, the archives are here: 2009, 2009).


Perl Advent Calendar Perl Advent goes way back, to the distant Y2K.


Web Performance Advent Calendar The Web Performance Calendar, started by yours truly last year, is coming back for another go — this time with many more contributors from companies like Google, Facebook, and Yahoo's own Nicholas Zakas, Mark Nottingham, Philip Telis, and Marcel Duran.


HTML5 Advent(ure) Calendar HTML5 Advent is the newest kid on the block. It doesn't have the usual article-a-day, but "24 days of killer demos, tutorials, community buzz..."


Any calendars I missed? Please add them via comments.

 

Announcing YUI Compressor 2.4.6

12:09 pm - April 26, 2011 in Yahoo! User Interface Blog

We’re pleased to announce the immediate availability of version 2.4.6 of the YUI Compressor. This version contains mostly updates related to Compressor’s handling of CSS minification and introduces batch processing of multiple files with a single command.

CSS minification

Highlights include:

  • Fixed numerous bugs that break the compressor and/or the resulting minified files.
  • Added documentation on what exactly the minifier does and also which CSS hacks it tolerates.
  • There’s a JavaScript port of CSS min in case it’s more suitable for your build process. Here’s also a test web UI that uses the JavaScript port, where you can experiment with the minifier.
  • A significant number of new tests added (but you can add even more).
  • Safe handling of some CSS features that are getting more adoption such as media queries and CSS3 transforms.

Batch processing

Another welcome addition to Compressor is that it can now handle batches of files. This can significantly reduce the time your build process takes, especially if you have a great number of files to minify.

For example the following commands minify all .js and .css files and write the minified files with a “-min.css” suffix.

$ java -jar yuicompressor.jar -o '.css$:-min.css' *.css
$ java -jar yuicompressor.jar -o '.js$:-min.js' *.js

Thanks go out to Stephen Woods and the Flickr team for this feature!

Links

YUI Compressor 2.4.6 is available for immediate download. Feel free to help us out by filing a bug or feature request, writing more tests, forking the code or joining the conversation.

 
 
 
 
 
 
It's All About Search | © clsc.net |
2012.05.1823:24
Tech used here: Valid HTML - Valid CSS - Valid RSS - JavaScript - PHP - Smarty - MySQL - and a partridge in a pear tree.