javascript - 为什么这一直说它没有定义

标签 javascript function object methods

使用firebug,它一直提示 this.speak 未定义,我不明白为什么会这样。我正在尝试将其输出到屏幕

 $(document).ready (function() {


    function person(rank, number, id) {
        //properties
        this.intRank = rank;
        this.intNumber = number;
        this.strId = id;
        this.elOutput = document.getElementById(id);
        //methods
        this.speak = fucntion(); {
            this.elOutput.innerHTML += "<br>" + this.strId;
        };

        //adds one to int number and speaks message
        this.pickUpNumber = function() {
            this.intNumber++;
            this.strId = "i have" + this.intNumber.toString() + "rocks";
            this.speak();
        };
    };

    //object

    var Jak = new person(5, "hey ,jack", " Captain");
    var Cap = new person(3, "yea cap?", "jacko");

    jak.speak(); cap.speak(); jak.pickUpRock();

});

最佳答案

this.speak = fucntion(); {
  this.elOutput.innerHTML += "<br>" + this.strId;
};

我认为你的意思是function()

并且JS是区分大小写的。

这可能就是您试图实现的目标:

$(document).ready (function() {
    function person(rank, number, id) {
      //properties
      this.intRank = rank;
      this.intNumber = number;
      this.strId = id;
      this.elOutput = document.getElementById(id);


      //methods
      this.speak = function() {
        this.elOutput.innerHTML += "<br>" + this.strId;
      };

      //adds one to int number and speaks message
      this.pickUpNumber = function() {
        this.intNumber++;
        this.strId = "i have" + this.intNumber.toString() + "rocks";
        this.speak();
      };
    }

    //object

    var jak = new person(5, "hey ,jack", " Captain");
    var cap = new person(3, "yea cap?", "jacko");

    jak.speak(); cap.speak(); jak.pickUpNumber();
});

结账 this工作 jsbin

关于javascript - 为什么这一直说它没有定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37516119/

相关文章:

javascript - 如何借助启用/禁用按钮禁用/启用表格中的整行?

javascript - 通过 JavaScript 将 onclick 与多个按钮结合使用

javascript - Jquery - 向表中添加新行(IE 友好版本)

matlab - MATLAB 是否允许您像 python 那样为函数的输入参数分配默认值?

c++ - 无法在没有对象的情况下调用成员函数 std::string class::function()

javascript - 关于node.js中passport.js模块 "deserializeUser"的效率

php - 复制功能

c++ - 递归函数有助于显示反向数字

c++ - 遍历指针 vector

java - 如何知道在创建对象时使用了哪个构造函数?