Objects in JavaScript (part II)

I will not write about prototypical inheritance in JavaScript today. Instead lets take a look at one misunderstanding:
“Changing prototype on the constructor will magically update not only new objects, but also all existing ones…”

This is totally wrong. Do not trust an author who uses word “magic” while explaining JavaScript (or anything).

function C() {} //constructor
var x = new C();
C.prototype.prop = 2;
var y = new C();
alert(x.prop);
alert(y.prop);

This code will alert “2” and “2”, which kind of proves quoted concept: object x gains new property prop after it was created. Magic? Not at all. Lets look at similar example:

function C() {} //constructor
var x = new C();
C.prototype = {prop: 2};
var y = new C();
alert(x.prop);
alert(y.prop);

This will alert “undefined” and “2”. Huh?

In the first case neither of objects (x or y) have property prop. What they have is a hidden reference to prototype. (Hidden, because only interpreter internally can access it.) When you ask for property prop JavaScript can’t find it in the object itself and look for it in linked prototype object, found it there and return it. So for you, as a programmer, it is no visual difference where property is stored: in the object itself or in its prototype. When you add new property to prototype object x didn’t change. When you ask for property prop JavaScript finds it in updated prototype.

In the second case we assign new object as a prototype. Now object x still refers to the old prototype, but object y refers to new. x and y do not share prototype anymore. Obviously old prototype doesn’t have property prop. Even worse, now you lost the only access point to it. Despite these two objects were created with the same syntax they are way different.

One more thing. As you know every object by default receives property constructor, which refers to its constructor (surprise). But just as prop constructor property doesn’t exists in object itself, but rather in its prototype. By rewriting prototype we rewrite constructor property as well:

alert(x.constructor); // "function C() {}"
alert(y.constructor); // "function Object() { [native code] }"

So, when you rewriting prototype you can’t rely on constructor property anymore. But rewriting prototype is a main technique of inheritance in JavaScript.

I will write about inheritance next time.

Objects in JavaScript (part I)

Recently I was talking to friend of mine about objects in JavaScript. He is writing JavaScript for living and very good at it, however I found that he doesn’t understand some core features of the language. So, in case you have this gap in understanding JavaScript, I’ll try to explain.

Friend of mine give cite me one book:

“The interesting thing about ECMAScript primitive values for Booleans, numbers, and strings is that they are pseudo-objects, meaning that they actually have properties and methods.”

I am really sorry, but this doesn’t make any sense.

First lets take a look at this example:

var a = 5;
a.t = 3;
alert(a.t);

It will alert “undefined”. Why? If “a” is a “pseudo-object” then why it doesn’t keep my property? The thing is, “a” is not an object. Not even “pseudo-object”. It is primitive number. It doesn’t have properties. As you know JavaScript convert variable from one type to another on the fly:

var b = "w" + a + [1, 2, 3];

In this example number “a” and array [1, 2, 3] will be converted to string on the fly. The same is happening with anything before “.” operator, JavaScript simply converts left hand side parameter to object. So, at the second line of the example JavaScript creates new object Number with value equals to “a” (5 in our case), then create new property “t” with value 3. But then this object is not assigned back to variable “a”, it is just disappear in garbage. Third line will again create new object and will try to read it property “t”, which is undefined.

Primitive types like boolean, number and strings are not objects, they could be converted to objects. What the rule? JavaScript has six built-in types: null, undefined, number, string, boolean and object. The conversion rule is simple: if input is object, leave it as is; if input is null or undefined, throw an exception; otherwise create new object (new Number(input) or new String(input) or new Boolean(input)). Hope this small bit will help somebody to understand objects in JavaScript a bit better. Next type I write about prototype and friends.

So, you think you know JavaScript?

Quick test for real understanding of JavaScript core beyond closures and scopes. Here five small scripts. Try to answer what will be alerted in each case without running them in the console. Then you could create a test file and easily check your answers. Ready?

if (!("a" in window)) {
    var a = 1;
}
alert(a);
var a = 1,
    b = function a(x) {
        x && a(--x);
    };
alert(a);
function a(x) {
    return x * 2;
}
var a;
alert(a);
function b(x, y, a) {
    arguments[2] = 10;
    alert(a);
}
b(1, 2, 3);
function a() {
    alert(this);
}
a.call(null);

Raphaël 0.7

New Raphaël release:

  • Plugins functionality (Raphael.fn.myshape = function () {};)
  • New method “set” as a replacement for depricated “group”
  • getBBox for text is fixed in IE
  • Added point of origin in rotation
  • Added support for “src” attribute in attr method
  • Added setWindow method for iframes support
  • Added setSize method, so you can resize canvas
  • Provide alternate simple syntax for gradients: “90-#000-#fff”, “‹angle›-‹colour›[-‹colour›[:‹offset›]]*-‹colour›”
  • Added multiline text support
  • Added event handlers: Element.click(function), Element.unclick(function)

Washington Post Using Raphaël

screenshot from washingtonpost.com
As stated on Ajaxian Washington Post start using Raphaël. Frankly, this is company named Evri, who is working for Washington Post and creates fancy widgets for them, uses Raphaël for drawing purposes. Anyway, Raphaël is on washingtonpost.com and it is time to celebrate. To see it by yourself you can visit this page.

WSG Talk

On 11 March 2009 I will be presenting Raphaël at Web Standards Group meeting. Come and join me.

Raphaël 0.6—Animation and More

Now, when I finally updated the documentation page, I feel ok to introduce you to Raphaël 0.6. So, what is new in this version?

  • Ability to set rotation, translation and scale via attr method
  • Ability to set path via attr method. That means now you can change path without redrawing it. The only thing you have to learn how to write path string in SVG documentation for path data syntax
  • New method animate, which takes three parameters: new attributes object, milliseconds and optional callback function
  • rotate method now has optional isAbsolute parameter which make it rotate object to specified degree, not by degree.

You could see the test demo and chart demo.

Also I created the Google group for Raphaël, so if you need some support or have feedback, please join the group.

Mac Shortcuts Converter

When switched to Mac it was a real disaster to understand all these special symbol OS uses for control keys (⌘, ⌥, etc). After a while I used to them and now I feel sorry for people who have to write “Command + Option + P” instead of “⌘⌥P”. To solve this little aesthetic issue I wrote a little application. Use it for good and let force be with you.

iPhone Clock Web Application

iPhone Clock

Since last year WebJam™ I am proud owner of shiny iPod Touch. Yes, still shiny. What I found recently that while I am in the office my iPod just wasting space at my desk. Just for fun I decide to create simple web application that will turn my iPod to digital clock while I am in the office.

Just for fun I decide to emulate old LC clock without any images or vector graphics. To make it look like application I have to put special meta tag inside HTML (<meta name="apple-mobile-web-app-capable" content="yes">). The problem with this method is that page doesn’t react to device rotation, but benefit of having custom digits is you can rotate them easily. So, don’t be surprised to see clocks rotated 90° in your browser. Here is a result.

Fig. 1 & Fig. 2

The question is, how I did all these fancy shapes without images? I was using borders. Take a look at fig. 1. If you apply wide border to some element and paint one side in different colour browser will solve graphical problem by creating “photo frame corner”. So, on fig. 2 I show idea: two narrow DIVs with wide borders will create a shape I need. Now in CSS I specify display rules depending on the value of the digit. I didn’t specify colour for borders so they could inherit colour from body text. Now to change colour of the clock I just need to change colour of the body. The rest is easy.

Hope you could pick up some interesting techniques from this example.

Update: Since iPhone/iPod software update 2.2 release had to update CSS a bit.

Raphaël Feed

I’ve created twitter account for Raphaël. All upcoming news and releases will be announced there. Feel free to follow @RaphaelJS or subscribe to RSS feed.

Web Directions South ’08 Wrap Up 2

Just want to point out that Web Directions crew finalised work on podcasts and podcast of my talk is available along with my slides at Web Directions web site, so look and listen if you feel like this.

Pie Chart Madness

With release of Raphaël 0.5.6b building pie charts become very easy task. Before I need to draw path with a hole inside, but now I can really draw every sector of the pie, because Raphaël finally has arcTo method. It was a bit of challenge to create it because VML has absolutely different interface from SVG. Fortunately Erik Dahlström from Opera point me to right direction. After that it was very easy to connect the points and have a good picture. Take a look at the demo of this lovely pie chart.
Image rotation on iPod with Raphaël

San Francisco

This Saturday (11 of October) I am travelling to San Francisco, California for two weeks. If anyone want to catch up for a coffee or something, feel free to drop me a line, because I probably will be bored after hours. Hope to see you there.