Wierd eval behavior

Discussion in 'Server and Client Scripting' started by Kalashnikov, Mar 27, 2012.

  1. Kalashnikov

    Kalashnikov Despite the code quality

    Joined:
    Apr 4, 2011
    Messages:
    434
    Likes Received:
    0
    Assuming
    Code (javascript):
    1.  
    2. if(!sys.require) {
    3.     sys.require = function(filename) {
    4.         return eval( sys.getFileContent('scripts/'+filename) );
    5.     };
    6. };
    7.  
    Suppose, I have a module A in a.js:
    Code (javascript):
    1.  
    2. function A() {
    3.     this.field = 'Lorem Ipsum';
    4. };
    5.  
    6. A.prototype.print = function() {
    7.     sys.sendHtmlAll(this.field);
    8. }
    9.  
    10. //sys.sendHtmlAll('hello from A');
    11. (new A())
    12.  
    And I use it this way:
    Code (javascript):
    1.  
    2. var A = sys.require('a.js')
    3. A.print();
    4.  
    But then script engine crashed with
    Code (text):
    1. TypeError: Result of expression 'A' [undefined] is not an object.
    2.  
    And the wierd part is that if I uncomment sys.sendHtmlAll('hello from A');, it works perfectly. Calling anything from sys object somehow fixes everything. In another module another problem occurs: inside class method (again, assigned via function prototype) this somehow turns out to be global script object, not an instance of that class. Again, a call to sys fixes everything.
     
  2. Lamperi

    Lamperi I see what you did there

    Joined:
    Apr 25, 2010
    Messages:
    2,647
    Likes Received:
    11
    It also works if you have just
    Code (text):
    1.  
    2. new A
    3.  
    instead of wrapping it into braces... which really does not make any sense.
     
  3. Kalashnikov

    Kalashnikov Despite the code quality

    Joined:
    Apr 4, 2011
    Messages:
    434
    Likes Received:
    0
    ...Or if I add a semicolon after last function declaration.
    So it is parsed as { /* ... */ }()
    Damn...
     
  4. Lamperi

    Lamperi I see what you did there

    Joined:
    Apr 25, 2010
    Messages:
    2,647
    Likes Received:
    11
    That's why optional semicolons are a bad idea...

    After function statement there should be no semicolon. After function expression there should be. Assigning an anonymous or named function to prototype is expression even if it looks like statement.