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

Closes #2632 and #2781
(cherry picked from commits 4defc519a1d22d7c4f3461b35bbaf1b9d9e3f59c)
and e8bfa5cee08f37e1e946e66ef88c60329944cfa0)