关于面向对象的javascript的困惑

时间:2011-08-02 18:02:55

标签: javascript oop

我在javascript中练习面向对象的语法,但是遇到了一些问题。这是我的代码:

<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>

当我加载页面时,正文的innerHTML是Name.protoype(“function()... this.first + this.middle + this.last ...”)的确切文本。我在这做错了什么?

4 个答案:

答案 0 :(得分:5)

您需要使用()运算符调用函数:

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

答案 1 :(得分:2)

您正在为原型分配一个函数,因此您需要按原样调用它:

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

答案 2 :(得分:2)

您需要调用您的函数:document.body.innerHTML = s.fullname();

示例here

答案 3 :(得分:2)

document.body.innerHTML = s.fullname;将innerHTML设置为函数s.fullname

如果你想将innerHTML设置为函数返回的,那么你需要实际调用该函数:

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