2011-12-28

Inheritance in JavaScript

JavaScript makes heavy use of objects, but its inheritance pattern is not like other object-oriented languages. Rather than class-based inheritance, JavaScript uses prototype-based inheritance. Objects are created by calling constructor functions with the new keyword. Every function has a prototype property that points to a prototype object. Any object instance has an implied reference to its prototype object (which may be null as well). Since the prototype is itself an ordinary object, it has a prototype too. This is what is called the prototype chain. When accessing a property of an object, the JavaScript engine tries to locate that property on the object itself. If it is not found on the object, it is searched in its prototype object and so forth.

The following code shows a simple example of using prototype-based inheritance.

  var Shape = function () {};
  Shape.prototype = Object.create(Object.prototype);
  Shape.prototype.area = function () {
    return new Error("Not implemented");
  };
  
  var Rectangle = function (width, height) {
    this.width = width;
    this.height = height;
  };
  Rectangle.prototype = Object.create(Shape.prototype);
  Rectangle.prototype.area = function () {
    return this.width * this.height;
  };
  
  var Square = function (side) {
    Rectangle.apply(this, [side, side]);
  };
  Square.prototype = Object.create(Rectangle.prototype);
  
  var square = new Square(16);
  console.log(square.area()); // prints 256

2010-05-20

The Sales Success Handbook

A few years ago, I had been asked by Adineh Publishing House to translate a book entitled The Sales Success Handbook by Linda Richardson. Recently, I noticed that the book has been published. If you are interested, you can order it online from adinebook.com.

چند سال قبل، مدير محترم انتشارات آدينه از من درخواست كرد كه كتاب موفقيت در فروش نوشته‌ي ليندا ريچاردسون را ترجمه كنم. اخيراً متوجه شدم كه كتاب چاپ شده است. اگر علاقه‌مند باشيد، مي‌توانيد كتاب را از adinebook.com سفارش دهيد.

2009-09-09

A Promise from God

بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيمِ

وَمَكَرُواْ مَكْراً وَمَكَرْنَا مَكْراً وَهُمْ لَا يَشْعُرُونَ

فَانظُرْ كَيْفَ كَانَ عَاقِبَةُ مَكْرِهِمْ أَنَّا دَمَّرْنَاهُمْ وَقَوْمَهُمْ أَجْمَعِينَ

فَتِلْكَ بُيُوتُهُمْ خَاوِيَةً بِمَا ظَلَمُواْ إِنَّ فِي ذَلِكَ لَآيَةً لِّقَوْمٍ يَعْلَمُونَ

وَأَنجَيْنَا الَّذِينَ آمَنُواْ وَكَانُواْ يَتَّقُونَ

النمل، 50-53

2009-01-22

Recursion and Local Variables in JavaScript

Consider the following JavaScript code snippet.

function f(x)
{
 var s = "";
 if(x instanceof Array)
 {
  s += "[";
  for(i = 0; i < x.length; i++) s += f(x[i]);
  s += "]";
 }
 else
 {
  s += "(";
  s += x.toString();
  s += ")";
 }
 return s;
}
alert(f([1, [2, 3, 4], 5]));

If you put this code in an HTML page, you will see that it shows the following result:

[(1)[(2)(3)(4)]]

What's wrong with the code?

The problem is that we have not defined the variable i in the for loop as a local variable. When the function f calls itself recursively, the variable i will have a value from the inner call, and the rest of the loop will not be executed in the outer call.

Now, we add var i; before the loop.

function f(x)
{
 var s = "";
 if(x instanceof Array)
 {
  s += "[";
  var i;
  for(i = 0; i < x.length; i++) s += f(x[i]);
  s += "]";
 }
 else
 {
  s += "(";
  s += x.toString();
  s += ")";
 }
 return s;
}
alert(f([1, [2, 3, 4], 5]));

Here is the result:

[(1)[(2)(3)(4)](5)]

Whenever we use recursion in JavaScript, it is particularly important to take into account the scope of local variables.

تراجع و متغيرهاي محلي در جاوااسكريپت

قطعه‌ي كد جاوااسكريپت زير را در نظر بگيريد.

function f(x)
{
 var s = "";
 if(x instanceof Array)
 {
  s += "[";
  for(i = 0; i < x.length; i++) s += f(x[i]);
  s += "]";
 }
 else
 {
  s += "(";
  s += x.toString();
  s += ")";
 }
 return s;
}
alert(f([1, [2, 3, 4], 5]));

اگر اين كد را در يك صفحه‌ي HTML قرار دهيد، مي‌بينيد كه نتيجه‌ي زير را نشان مي‌دهد:

[(1)[(2)(3)(4)]]

مشكل اين متن برنامه در كجا است؟

مسئله آن است كه ما متغير i را در حلقه‌ي for به عنوان يك متغير محلي تعريف نكرده‌ايم. وقتي كه تابع f خودش را به صورت تراجعي فرا مي‌خواند، متغير i از فراخواني داخلي، داراي مقدار خواهد بود و بقيه‌ي حلقه در فراخواني خارجي اجرا نخواهد شد.

حالا يك سطر var i; قبل از حلقه اضافه مي‌كنيم.

function f(x)
{
 var s = "";
 if(x instanceof Array)
 {
  s += "[";
  var i;
  for(i = 0; i < x.length; i++) s += f(x[i]);
  s += "]";
 }
 else
 {
  s += "(";
  s += x.toString();
  s += ")";
 }
 return s;
}
alert(f([1, [2, 3, 4], 5]));

نتيجه از اين قرار است:

[(1)[(2)(3)(4)](5)]

هر گاه در جاوااسكريپت از تراجع استفاده مي‌كنيم، اين موضوع اهميت خاصي دارد كه به قلمرو متغيرهاي محلي توجه كنيم.

2008-11-18

The Brass Verdict

The Brass Verdict by Michael Connelly

The Brass Verdict, by Michael Connelly, is an account of corruption and hypocrisy. Featuring both Harry Bosch and Mickey Haller, it is, to some extent, reminiscent of Personal Injuries, by Scott Turow. The name refers to the brass jacket of rounds shot from a German-made Mauser gun.

I have read all of the fiction books by Michael Connelly, and this seems to be the best so far. Before that, I read the Hot Mahogany, the latest Stone Barrington novel, by Stuart Woods. (Ironically, I have read almost all previous books featuring this character, but in reverse order. Can you believe it?) Stuart Woods is certainly a great author, but, in my opinion, Michael Connelly is a lot better. More and more, he succeeds in polishing and advancing the genre of noir detective fiction.

The overwhelming cliché in Harry Bosch novels is the corrupt police. The idea behind the Lincoln Lawyer was a true villain, a real and heinous evil being. Though I hate to write spoilers, suffice it to say that this new one is about corruption on another level of authority. My point is that this book refers to a very relevant topic considering the actual state of our society. I did relish this novel and I do recommend it to all readers interested in crime fiction.

2008-09-15

Musings on Writing

I am currently reading “The Bourne Sanction” by Eric Van Lustbader and Robert Ludlum. It is a really good book. I haven’t read the three previous Bourne installments, but I have watched their respective movies. I wished I had read those three books that have been written by the late Ludlum himself, so that I can do a better appraisal of the prose of this book. Nevertheless, it has a superb prose and I like it very much.

Thrillers like other kinds of literary work consist of several dimensions. One dimension is the element of suspense and plot. No objection to that. But the prose is important, as well. One of my favorite authors, who is a bestselling author in the thriller genre, does not enjoy a particular power in writing fluent prose. This I regret. He is my real favorite because of his school of thought and so on.

The importance of the element of balance cannot be overemphasized. I hate books laden with lengthy, descriptive passages which are of no avail to the main objective of the book. There are plenty of such compulsory writers, some of them even famous in literary circles. But for someone like me who is interested in good thriller books, the artistic element of the book must be in a delicate balance with its being a hilarious thriller.

The element of humor and the writer’s personality sometimes gets very outstanding and ruins the book to some extent. The mood and morality of the author should not be conspicuous in a fiction book. This is another place where balance plays an important role.

So much for musing in a field I have no expertise in. Today, I became 38. On to a better year I hope.

2007-08-03

Harry Potter and the Deathly Hallows

Last week I finished reading the seventh book in the Harry Potter series, "Harry Potter and the Deathly Hallows", and it was a very pleasurable experience. Since I am not going to spoil your reading of the book, I don't make any remarks as to the plot of the book. Ever since the publication of previous volume of the saga, which I have translated into Persian and you can download it for free, I occasionally worried that the last volume may disappoint me. There were some loose ends in the previous tomes, which couldn't help but make me more anxious to read the last installment. Well, here it is-much better than I could ask for.

While I was reading the seventh book, I got a feeling that it was written in a more fluent language, with lesser use of "dictionary" and "strictly British" words. This makes its translation much simpler. A word of thanks is due to Ms. Rowling for this! Moreover, this volume, enjoying a coherent and compelling plot, is a real page-turner. The ending is almost as I wished it to be. Since I don't like to read fan fiction, I am looking forward to reading more books written by JK Rowling in the future.

The Persian translations that sprang into being all over the net immediately after the release of the book (even before its release in some instances) prevented me form considering this volume for translation. There are a lot of good books out there waiting to be translated (and to be read, I hope—though, sometimes, the lack of book reading in my country is disappointing!)…

«هري پاتر و يادگارهاي مرگ»

هفته‌ي گذشته كتاب هفتم مجموعه‌ي هري پاتر را، كه ترجمه‌ي پيشنهادي من براي عنوان آن «هري پاتر و يادگارهاي مرگ» است، خواندم و بايد بگويم كه كتاب بسيار خوبي بود. البته قصد ندارم به ماجراي داستان اشاره كنم تا لذت كساني را كه هنوز نخوانده‌اند، از بين نبرم. از زمان انتشار جلد قبلي، هميشه ترسم اين بود كه آخرين كتاب داستان خوبي نداشته باشد و توقعات زيادي را كه از هري پاتر در خوانندگان پيدا شده است، بر آورده نكند. علاوه بر اين، معماهاي حل نشده‌اي در جلد قبل مطرح شده بود كه اشتياق مرا براي خواندن جلد آخر بيشتر مي‌كرد. بالاخره كتاب منتشر شد و حتي از حد انتظار من هم بهتر بود.

در حين خواندن كتاب هفتم، احساس كردم كه اين جلد روان‌تر نوشته شده و كمتر از كلمات لغتنامه‌اي و «مطلقاً بريتانيايي» استفاده كرده است. به نظر من، در اين مورد بايد از خانم رولينگ سپاسگزار باشيم! به علاوه، اين جلد از داستاني همخوان و گيرا برخوردار است كه سبب مي‌شود كتاب را نتوان در حين خواندن به سادگي زمين گذاشت. پايان داستان تقريباً همان جوري است كه من آرزويش را داشتم. چون من از خواندن كتاب‌هاي هواداران (fan fiction) خوشم نمي‌آيد، اميدوارم در آينده نيز كتاب‌هاي بيشتري از جي.كي. رولينگ بخوانم.

از اولين لحظات انتشار كتاب هفتم (و در برخي از موارد، حتي از قبل از انتشار رسمي كتاب)، ترجمه‌هاي متعددي به زبان فارسي در اينترنت ظاهر شد، و همين امر سبب شد كه من حتي فكر ترجمه كردن اين جلد را به سرم راه ندهم. كتاب‌هاي خوب زيادي براي ترجمه هست (البته اميدوارم كه خواننده هم داشته باشد—بعضي وقت‌ها كم بودن كتابخواني در ايران خيلي آزارم مي‌دهد!)…