I'm trying to pass document.write
as a reference to a variable:
Example:
var f = document.write
//then
f('test');
It works with alert. Why doesn't it work with document.write
?
Because alert
doesn't care what this
is (alert
is a global) and document.write
does (it needs to know which document it is writing to).
If you want a wrapper, then write a shortcut function.
function f(str) { document.write(str); }
… and then go and ritually disembowel yourself for calling the variable f
. Self-describing is a virtue of good code.
In addition to what's already said, Javascript 1.8.5 has a native solution for the problem : the bind function
f = document.write.bind(document)
f("hello")
The link above also contains emulation code for browsers that don't support JS 1.8.5 yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With