0

Okay, this may be a silly question but I'm still on my path to learning OO javascript like a pro, so please don't laugh if this question is a little dumb... okay, say I have a very simple object like this

var myObject = {

    write:function(){
        return 'this is a string';

    }
}

now if add the following outside my object (please note I have the appropriate Div in my webpage):

document.getElementById('myDiv').innerHTML = myObject.write();

the innerHTML of my div is filled with the string 'this is a string', however if I just add the following to my script (outside the object): myObject.write()

nothing is returned? Can some one tell me why and how I could write to the page ( not using document.write(myObject.write()) ) to output the string to the page. If this can't be done please let me know why...

sorry if this is a really simple / stupid question but I am learning.

Here's the full thing to help...

<html>
<head>
</head>

<body>

<div id='myDiv'></div>

<script type="text/javascript">

var myObject = {

    write:function(){
        return 'this is a string 2';

    }
}

//document.getElementById('myDiv').innerHTML = myObject.write();
myObject.write();

</script>

</body>
</html>

2 Answers 2

4

Calling myObject.write() returns the value. Since you're not catching and processing the return value, nothing happens.

Another method to write content to your document:

<body>
<script>document.write(myObject.write())</script>
...</body> <!--document.write ONLY works as desired when the document loads.
       When you call document.write() after the document has finished initiating,
       nothing will happen, or the page unloads-->
Sign up to request clarification or add additional context in comments.

3 Comments

@Mark -- haha that is true, did not realize that you wanted such a simple answer ^_^
Hey! I said no document.write, don't make me mark your answer down Rob L, LOL! Thanks too Neal
I design my answers to be useful to the asker, and to future readers. This site gets much traffic from Google and other search engines.
0
var myObject = {
    obj: (function(){ return document.getElementById('myDiv');})(),
         //^^set object to write to
    write:function(str){
        this.obj.innerHTML += str;
        //^^add the string to this object
    }
}

myObject.write('hello there');

Demo: http://jsfiddle.net/maniator/k3Ma5/

2 Comments

What's the purpose of the self-invoking function here?
@pimvdb to get the object immediately

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.