0

Below is some example code that explains the error:

HTML:
<!DOCTYPE HTML>
<html>
<head>
  <title>Test</title>
</head>
<body>
  <h1>Widget Test</h1>
  <script type="text/javascript">
    (function() {
      var script = document.createElement('script'); script.type = 'text/javascript';           
      script.async = true;
      script.src = 'http://localhost/job/widget.js';
      var s = document.getElementsByTagName('head')[0].appendChild(script);
    })();
  </script>
  <div id="list" data-cnumber="21"></div>
</body>
</html>


widget.js:

(function() {
  var a = new app();
  var a1 = new app1();

  function app() {
    this.a;
    this.b;
  }
  app.prototype.add = function () {

  };

  function app1() {
    this.a;
    this.b;
    this.c;
    this.add();
  }
  app1.prototype.add = function () {

  };
})();
  1. This is the error - "Uncaught TypeError: Object # has no method 'add' "
  2. On doing console.log of both the objects, I can see their properties, but for some reason not their methods.

What's wrong?

4

2 に答える 2

1

コンストラクターを既に呼び出した後にプロトタイプメンバーを作成しているため、コンストラクターの呼び出し中には使用できません。コンストラクターを呼び出す前に作成する必要があります。

(function() {
  app.prototype.add = function () {

  };
  app1.prototype.add = function () {

  };

  var a = new app();
  var a1 = new app1();

  function app() {
    this.a;
    this.b;
  }


  function app1() {
    this.a;
    this.b;
    this.c;
    this.add();
  }

})();
于 2013-09-28T19:12:29.090 に答える