Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Created June 30, 2014 07:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DmitrySoshnikov/b135eb17ff5997e4f1e7 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/b135eb17ff5997e4f1e7 to your computer and use it in GitHub Desktop.
/**
* Apply a function in needed environment.
* Firefox only, educational purpose only.
* by Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
*/
Function.prototype.setEnvironment = function(environment) {
with (environment) {
return eval(uneval(this));
}
};
(function () {
return x + y;
})
.setEnvironment({x: 10, y: 20})
.call(); // 30
@WebReflection
Copy link

why Firefox only ?

Function.prototype.setEnvironment = function(environment) {
  with (environment) {
    return eval('(' + this + ')');
    // or a more paranoid ….
    return eval('(' + Function.toString.call(this) + ')');
  }
};

@DmitrySoshnikov
Copy link
Author

@WebReflection, yeah, explicit toString works well in other browsers too. I just made it idiomatic uneval-eval sequence, and since the uneval isn't standardized (and behind the scene probably does toSource() rather than toString()), mentioned Firefox only.

Though, it's not for JS usage. This snippet is only for explaining generic concept, that without an environment function doesn't make sense. But once we provide the environment, the function has already runtime meaning.

Although, probably with this snippet it's possible to fake some private module data. If some function uses private vars of a module, and at the same time calls some this-methods, you may facilitate the private vars with your values.

var M = (function () {
  var privateData = 'privateUserId';
  return {
    send: function() {
      // ...
      // work with private user id data
      // ...
      console.log(privateData);
    }
  };
}());

M.send(); // private

M.send
  .setEnvironment({privateData: 'fakeUserId'})
  .call(M); // fake

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment