【问题标题】:Javascript confusing Object function "has no method" errorJavascript混淆对象函数“没有方法”错误
【发布时间】:2012-02-11 01:12:16
【问题描述】:

所以我有一个看起来像这样的函数:

function Students(){
  // Function add:
  //  Returns: add page
  this.add = function(){

  // Get template
  $.get('view/students/new.html', function(template){

    // Templating
    var html = Mustache.to_html(template);

    // When document ready, write template to page
    $('document').ready(function(){
      $('#container').html(html);
    });
  });
};

};

当我尝试像这样调用它的 add 函数时:
Students.add();

我得到错误: Uncaught TypeError: Object function Students(){...}has no method 'add'

什么给了?

【问题讨论】:

    标签: javascript function object


    【解决方案1】:

    要使用Students 的实现,您应该这样做:

    var students = new Students();
    students.add();
    

    但是,这可能不是您想要的。您可能打算像这样定义Students

    var Students = {
        add: function() {
             $.get( /* ... */ );
        }
    };
    

    那么你可以这样称呼它:

    Students.add();
    

    【讨论】:

      【解决方案2】:

      您没有使用该代码向“学生”函数添加“添加”函数;您正在将其添加到使用“Students”作为构造函数创建的实例中。

      var student = new Students();
      
      student.add(); // won't get the error
      

      【讨论】:

        【解决方案3】:

        学生被称为构造函数

        var s = new Students();
        s.add()
        

        Students 内部,this 将是一个继承自 Student 原型的新对象,并自动返回。这么说

        this.add = function() ....
        

        正在将add 函数添加到正在返回的这个对象上。但是每次调用此函数时,都会从头创建该函数。为什么不将它添加到原型中,这样函数只会存在一次,而不必每次都不必要地重新创建。

        Students.prototype.add = function(){
        

        【讨论】:

          【解决方案4】:

          好吧,Students 没有 add 方法。

          我想你假设你知道this 是如何工作的。它不是对该函数的引用,除非您手动设置它。 this 的值将完全取决于如何您调用Students

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-06-24
            • 1970-01-01
            • 2018-04-20
            • 2011-12-17
            • 2013-01-01
            • 1970-01-01
            相关资源
            最近更新 更多