2

Say I have the following function

function foo(){
    console.log(test);
    console.log(window);
}

Is there a way to prevent foo to access the window object ? I've tried the following

foo.apply({});

But it only changes the this and leaves access to window

2
  • 3
    Why would you need such a thing ? Commented May 11, 2014 at 17:46
  • The function's scope is (nearly) always a descendant of the global scope, you hardly can restrict that (and it would make the script no longer work) Commented May 11, 2014 at 17:52

1 Answer 1

1

You can use var window = {}; to override the reference to the global object. You can additionally use the .apply({}) method to prevent access via this.

However, nothing you can do will stop undeclared variables from being get/set on the global object, short of manually defining every possible variable name...

As Bergi points out, window = (function() {return this;}()); will restore the reference to the window object. This is again something that probably cannot be stopped.

Sign up to request clarification or add additional context in comments.

3 Comments

And how would you prevent anyone from restoring the reference, e.g. by window = (function(){return this;}()); (or eval magic if in strict mode)?
@Bergi Huh, that's a good one. Didn't occur to me XD But since my answer is basically saying "you can make it difficult, but there are ways", the point is the same.
(function(){return this;}()) will not work in strict mode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.