2012-03-27

Property Assignment and hasOwnProperty

An important task in JavaScript development is to check if a property has already been assigned a value. There are two ways to check for the presence of a property in an object. The first method, prop in obj, checks the existence of the property in the object or in its prototype chain. The second method, obj.hasOwnProperty(prop), checks if the property exists on the object itself.

If a property exists on the object’s prototype, it is masked by an assignment of that property on the object itself. Consider the following code snippet:

(function () {
 var p = {
  name : "human",
 };
 var a = Object.create(p);
 console.log(a.name); // human
 console.log(a.hasOwnProperty("name")); // false
 a.name = "Ali";
 console.log(a.name); // Ali
 console.log(a.hasOwnProperty("name")); // true
})();

Noting these results, it would seem appropriate to use hasOwnProperty as a test for checking whether the property has been assigned a value on the object proper. But this leads to an unexpected result in the particular case of “accessor” properties:

(function () {
 var p = Object.defineProperties({
   _age : 0,
  }, {
   _age : {
    enumerable : false,
   },
   age : {
    get : function () {
     return this._age;
    },
    set : function (age) {
     if (isNaN(age) || (age < 0)) {
      throw new Error("Invalid value for age: " + age);
     }
     this._age = age;
    },
    enumerable : true,
    configurable : true,
   },
  });
 var a = Object.create(p);
 console.log(a.age); // 0
 console.log(a.hasOwnProperty("age")); // false
 a.age = 14;
 console.log(a.age); // 14
 console.log(a.hasOwnProperty("age")); // false
})();

This example shows that “accessor” properties of the prototype are not masked by value assignment on the descendent object. Consequently, hasOwnProperty cannot detect value assignment in these cases.

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 () {
    throw 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.