diff --git a/lib/vm.js b/lib/vm.js index d3348afac5..75049e5185 100644 --- a/lib/vm.js +++ b/lib/vm.js @@ -21,12 +21,34 @@ var binding = process.binding('evals'); -exports.Script = binding.NodeScript; -exports.createScript = function(code, ctx, name) { - return new exports.Script(code, ctx, name); +module.exports = Script; +Script.Script = Script; + +function Script(code, ctx, filename) { + if (!(this instanceof Script)) { + return new Script(code, ctx, filename); + } + + var ns = new binding.NodeScript(code, ctx, filename); + + // bind all methods to this Script object + Object.keys(binding.NodeScript.prototype).forEach(function(f) { + if (typeof binding.NodeScript.prototype[f] === 'function') { + this[f] = function() { + if (!(this instanceof Script)) { + throw new TypeError('invalid call to '+f); + } + return ns[f].apply(ns, arguments); + }; + } + }, this); +}; + +Script.createScript = function(code, ctx, name) { + return new Script(code, ctx, name); }; -exports.createContext = binding.NodeScript.createContext; -exports.runInContext = binding.NodeScript.runInContext; -exports.runInThisContext = binding.NodeScript.runInThisContext; -exports.runInNewContext = binding.NodeScript.runInNewContext; +Script.createContext = binding.NodeScript.createContext; +Script.runInContext = binding.NodeScript.runInContext; +Script.runInThisContext = binding.NodeScript.runInThisContext; +Script.runInNewContext = binding.NodeScript.runInNewContext;