I think Javascript is trying to kill me. Errors that would be caught by a compiler in any statically-typed language including FORTRAN, or turn into a run-time exception in any decent dynamically-typed language are swallowed silently by Javascript, patiently waiting to manifest as a bug elsewhere.
Whenever we write Frontend code (nowadays with Angular), we spend most of our time hunting down mistakes such as writing $scope.result = data.results
instead of data.result
. While some tools help, it still requires an astonishing amount of work.
Is there a way to cause the Javascript environment (in a browser) to log a warning whenever someone tries to read a non-existing object property? I don't want to change the language's semantics - accessing data.results
should still returned undefined
, I just want to see a warning on the console saying "Non-existing property accessed, file ... line ...".
This is a duplicate of this question I think : Force JavaScript exception/error when reading an undefined object property?
In short : no satisfying solution for your use case, but if you all use firefox you can use javascript.options.strict
set to true to have warning in such cases :)
In ECMAScript 2015 you can use Proxy to do this, for example:
function createObject(obj) {
const handler = {
get: function(target, name){
if (name in target) {
return target[name];
} else {
console.warn("accessing undefined object property: " + name);
return undefined;
}
}
};
return new Proxy(obj, handler);
}
let a = createObject({
b: 1,
c: undefined
});
a.b;
a.c;
a.d; // accessing not existing object property: d
This might seem amateurish, but you might be able to store all of your variables in a loop able object like an array or object and then loop through them to check if any of them are undefined
, then print the results of that. You might be able to use a dictionary with key:value
pairs. Not ideal, though.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.