The following program prints “Hello world” as expected
var print = function(t){
document.write(t);
};
var printAlias = print;
printAlias("Hello world");
But when I use the same technique with document.write it does not work.
var write = document.write ;
write("Something);
Can anybody tell me what am I missing?
It doesn’t work because you’ve lost the context (the “
thisvalue”) within thewritemethod ofdocument. You can invokewritewith thecallmethod to get it back:In your first example you are simply wrapping the call to
document.writein another function, but the call itself keeps the context because you invokewriteas a method ofdocument.So you may as well stick with the usual or your wrapper function if it’s shorter code you were aiming for! Or (thanks @Esailija) you could bind the context to
documentat the time you create yourwritevariable: