Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript saving document.write in a variable and calling it

Tags:

javascript

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?

like image 230
Marcelo Noronha Avatar asked Oct 19 '11 19:10

Marcelo Noronha


2 Answers

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.

like image 100
Quentin Avatar answered Nov 05 '22 14:11

Quentin


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.

like image 36
georg Avatar answered Nov 05 '22 12:11

georg