Ensure scope 'this' is properly restored, add unit test.

Close #2632
Merge pull request #709 from sigurdteigen/fix/restore-this-scope

Ensure scope 'this' is properly restored, add unit test.