1

I'm practicing object oriented syntax in javascript and am having some problems. This is my code:

<html>
<head>
     <script type="text/javascript">
          function Name(first,mid,last) {
               this.first = first;
               this.middle = mid;
               this.last = last;
          }
          Name.prototype.fullname = function () {
               return this.first + " " + this.middle + " " + this.last;
          }
          Name.prototype.fullnamereversed = function() {
               return this.last + " " + this.middle + " " + this.first;
          }
          var s = new Name("James","Harlow","Smith")
</script>
</head>
<body>
     <script type="text/javascript">
          document.body.innerHTML = s.fullname;
          document.body.innerHTML = s.fullnamereversed;
     </script>
</body>
</html>

When I load the page, the innerHTML of the body is the exact text of Name.protoype ("function ()... this.first + this.middle + this.last..."). What have I done wrong here?

1
  • This question is similar to: Javascript function call with/without parentheses. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Oct 17 at 7:00

4 Answers 4

4

You need to call the functions with the () operator:

document.body.innerHtml = s.fullname();
Sign up to request clarification or add additional context in comments.

1 Comment

Silly mistake on my part. Thank you.
1

You are assigning a function to the prototype, therefore you need to call it as such:

<script type="text/javascript">
document.body.innerHTML = s.fullname() + ' ' + s.fullnamereversed();
</script>

Comments

1

You need to invoke your function: document.body.innerHTML = s.fullname();

Example here.

Comments

1

document.body.innerHTML = s.fullname; sets the innerHTML to the function s.fullname.

If you want to set the innerHTML to what the function returns, then you need to actually call the function:

document.body.innerHTML = s.fullname();

Comments

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.