Skip to content

Instantly share code, notes, and snippets.

@tcr
Last active November 29, 2017 03:38
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tcr/4416956 to your computer and use it in GitHub Desktop.
Save tcr/4416956 to your computer and use it in GitHub Desktop.
Make a callable() object in all browsers and Node.js
if (!Object.__proto__) {
var sandbox = function () {
// create an <iframe>
var iframe = document.createElement("iframe");
iframe.style.display = "none";
document.documentElement.appendChild(iframe);
return frames[frames.length - 1];
}
var iframe = sandbox();
iframe.document.write("<script>parent.Callable = function (F) { var C = function () { var obj = function () { C.prototype.call.apply(this, arguments); }; F.apply(obj, arguments); return obj; }; C.prototype = Function.prototype; return C; }; parent.Callable.prototype = Function.prototype;<\/script>");
} else {
this.Callable = function (F) {
var C = function () {
var obj = function () {
C.prototype.call.apply(this, arguments);
};
obj.__proto__ = C.prototype;
F.apply(obj, arguments);
return obj;
};
return C;
};
}
var API = Callable(function () {
this.prop = 'and a property value .prop';
});
API.prototype.call = function (arg) {
console.log(arg);
};
API.prototype.boss = function (arg) {
console.log(arg, this.prop);
};
var a = new API();
a('.call() invocation');
a.boss('.boss() invocation');
@shesek
Copy link

shesek commented Jan 26, 2013

Heh, I just wrote something very similar (https://gist.github.com/4636379, CoffeeScript) and found that. Your solution for browsers without proto is very clever, nice work!

Shouldn't you create a separate sandbox for every callable tho?

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