Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: prevent unintentional creation of new property

Typos happen, and sometimes it is really hard to track them down in JavaScript. Take this for example (imagine it in between some more code):

// no error. I would like a warning
document.getElementById('out').innerHtml = "foo";

For undeclared variables, strict mode helps:

"use strict";
var myHTML = "foo";
myHtml = "bar"; // -> error

But it does not work for the example above. Is there a program or mode that can catch these bugs? I tried JSLint and JavaScript Lint, but they do not catch it.

And ideally, I would like this to still work (without warning):

// should work (without warning)
function MyClass(arg) {
  this.myField = arg;
}
like image 313
tim Avatar asked Oct 31 '22 19:10

tim


2 Answers

Using an IDE like WebStorm helps a lot in detecting this kind of errors.

To prevent accidentally adding properties to an object, you can freeze it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

With ES6, you could use proxies to detect these errors: http://www.nczonline.net/blog/2014/04/22/creating-defensive-objects-with-es6-proxies/

like image 184
Jos de Jong Avatar answered Nov 12 '22 17:11

Jos de Jong


Well, thats the price of dynamically typed programming languages. because it is possible to add properties at runtime, there is no real solution to detect typos in code.

you could however add an innerHtml function to the Element prototype, internally calling innerHTML to eliminate certain typos, but I definately wouldn't recommend that.

As other comments already suggested: A good IDE can help you identifiying typos. I'm only working with WebStorm and VisualStudio which both are able to detect undeclared or unused functions.

like image 23
Sabacc Avatar answered Nov 12 '22 16:11

Sabacc