Problem when using JavaScript keyword in code
January 14, 2011 Leave a comment
It is well known advice/rule in programming that you must not use keywords in your own code (considered cases when programming language gives ability to do it). But sometimes when programmer is overtired may forget this rule and builds a huge logic and writes a big amount of code using language keywords. And then flow of code execution goes wrong or illogically. What is effective solution of this kind of situations?
Let’s discuss it when coding in JavaScript. For example, if you have defined array of this kind of objects:
{ title : 'Employees', root : 'employeesList', display : 'always', constructor: { fn : someFunction, config : { rootVisible : false, listeners: { click: function(node) { alert('Not implemented yet!'); } } }, type : 'tree', children : 'subEmployees', getText : function(node){ return node.text || 'EMPTY'; } } }
Object looks quite complicated, there is used JavaScript’s keyword constructor, I’ve array that contains objects of this kind and have build logic on this array. Once I needed to check if i-th object had property constructor and as usual I wrote:
for(var i=0; i<array.length; i+=1){ if(array[i].constuctor){ alert('has property constuctor'); }else{ alert('doesn\'t have constructor'); } }
The result always was: has property constuctor. Of course it would have!!! 😀 why? Because every JavaScript object has property constructor since every object is directly or indirectly inherited from Object function (or class in this case) and Object.prototype object contains property constructor that is reference to function which created that object. So, every JavaScript object has property constructor because JavaScript language defines Object.prototype.constructor as reference to function that created object. (new ThisWillBeReturnedByConstructorPropertyOfObject() ), more shortly “constructor” is keyword :).
When I realized it I was confused for a second but then I remembered about function hasOwnProperty that also have every object (because Object.prototype.hasOwnProperty is defined by language). This function gets one parameter -{String} property of an object. And returns Boolean true if object has not inherited property and has defined it itself. So I changed my code like this and everything was corrected:
for(var i=0; i<array.length; i+=1){ if(array[i].hasOwnProperty("constuctor")){ alert('has property constuctor'); }else{ alert('doesn\'t have constructor'); } }
I do not provoke writing a bad code. All I wanted to say is that, unfortunately, if you have written a bad code, that I described above, there is a way by which you can go around of problem by a little change. In the most cases programmers do not have enough time to spend on not scheduled tasks.