0

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?

1 Answer 1

2

It doesn't work because you've lost the context (the "this value") within the write method of document. You can invoke write with the call method to get it back:

write.call(document, "Something");

In your first example you are simply wrapping the call to document.write in another function, but the call itself keeps the context because you invoke write as a method of document.

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 document at the time you create your write variable:

var write  = document.write.bind(document);
Sign up to request clarification or add additional context in comments.

5 Comments

He might as well var write = document.write.bind( document ) since write.call is not supported in older IE anyway
@Esailija - Yeah true. I didn't know that it wasn't supported in older IE. Which version did that get fixed in?
Ok. So the write method uses "this" somewhere inside and expects "this" to be document. Am I right?
@JamesAllardice I am not really sure, I just remember older IE not even defining .call on DOM functions
@Esailija - Yeah that rings a bell. I rarely use .call or .apply on DOM methods and need to support old IE. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.