Last active
November 29, 2017 03:38
-
-
Save tcr/4416956 to your computer and use it in GitHub Desktop.
Make a callable() object in all browsers and Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?