0

I am seeing if there is a build time (using Grunt or maybe JSHint) to only use defined object references. Given this object, throw an error at build (parse) time if referencing an undefined property:

var o = { 
    foo: 'has a value.',
    num: 42
}

console.log('This string ' + o.foo) // Valid
console.log('Summing: ', o.num + o.doesntExistNumber) // Throws an error

For context I want to use this with Angular JS's "constant" service, so the object should be immutable in the application. Any suggestions?

beeryardtech
  • 605
  • 1
  • 4
  • 15
  • How about Object.freeze() with 'use strict'? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze – RB-Develop Mar 31 '14 at 13:49
  • I really doubt such checks are possible. Remember that even though `doesntExist` property is not defined on `o`, it may be defined for `o.__proto__` - or anywhere up the prototype chain. I guess the best bet for you is using TypeScript or some similar compiled-to-JS language, allowing to introduce more strictness in JS code. ) – raina77ow Mar 31 '14 at 13:52
  • If you use WebStorm or PhpStorm or IntelliJ you would detect the non-existent property in the editor (in almost all cases). – hgoebl Mar 31 '14 at 14:38
  • The `Object.freeze()` approach looks interesting. However that limits it to run time checking. Hoping for an option in jshint/jslint. At worst could use a `sed`script option... – beeryardtech Apr 09 '14 at 19:20
  • possible duplicate of [circular references among javascript functions](http://stackoverflow.com/questions/17269283/circular-references-among-javascript-functions) – Paul Sweatte Oct 01 '14 at 01:21

0 Answers0