当我尝试在jquery mobile中使用对象方法时代码中断

时间:2016-01-16 01:08:34

标签: javascript jquery class object jquery-mobile

这是我的班级

var Player = function (name) {

        this.init(name);

    }

    $.extend(Player.prototype, {

        Name: '',
        Goals: 0,
        Fouls: 0,
        Holding: 0,
        Games: 0,
        Wins: 0,
       Taken: 0,


       init: function(name){

           this.Name = name;
           this.Goals= 0;
           this.Fouls= 0;
           this.Holding= 0;
           this.Games= 0;
           this.Wins= 0;
           this.Taken= 0;

       },
        setGoal: function (num) {
            this.Goals+= num;

        },
        setFouls: function (num) {
            this.Fouls+=num;
        },
        setHolding: function (holding) {
            this.Holding = (this.Holding * (this.Games-1) + holding) / (this.Games);
        },
        setGames: function () {

            this.Games+=1;
        },
        setWins: function () {

            this.Wins+=1;
        },
        setTaken: function (num) {

            this.Taken+=num;
        }
 });

我尝试了很多东西,但是花了很多时间我试图在创建这个类的实例之后尝试访问一个方法,它只是休息而且不要让我继续。

2 个答案:

答案 0 :(得分:0)

我没有看到你使用正在使用的构造函数。

应该这样使用:

var Player = function(name) {
  this.init(name);

}

$.extend(Player.prototype, {

  Name: '',
  Goals: 0,
  Fouls: 0,
  Holding: 0,
  Games: 0,
  Wins: 0,
  Taken: 0,


  init: function(name) {

    this.Name = name;
    this.Goals = 0;
    this.Fouls = 0;
    this.Holding = 0;
    this.Games = 0;
    this.Wins = 0;
    this.Taken = 0;

  },
  setGoal: function(num) {
    this.Goals += num;

  },
  setFouls: function(num) {
    this.Fouls += num;
  },
  setHolding: function(holding) {
    this.Holding = (this.Holding * (this.Games - 1) + holding) / (this.Games);
  },
  setGames: function() {

    this.Games += 1;
  },
  setWins: function() {

    this.Wins += 1;
  },
  setTaken: function(num) {

    this.Taken += num;
  }
});
var p = new Player('Rayon');
p.setGoal(10);
alert(p.Name +' has scored '+p.Goals +' goals');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

答案 1 :(得分:0)

显然我最初使用的是构造函数,我忘了使用本地存储来维护,对象文件是可以的,但是当我尝试使用这些方法时,代码会中断。