How to declare member functions in javascript? Getting "TypeError: Object.function is not a function"

How to declare member functions in javascript? Getting "TypeError: Object.function is not a function"

我来自 java 背景,我正在尝试以 java 风格的方式声明成员。为什么我的函数对外不可见或者不被识别为函数?从函数内部为函数声明成员函数的正确方法是什么?

function Animation() {
  var draw = function draw() {
      ...
  };

  var move = function move() {
    ...
  };
}

function startAnimation() {
  ...
  var animation = new Animation();
  function frame() {
    ...
    animation.move()
    animation.draw();
    ...
  }
}

执行代码时,我在控制台中收到错误消息:

TypeError: Object.function is not a function

动画是一个函数而不是一个对象试试这个

var Animation = {
    draw: function() {
     ...
    },

    move: function() {
     ...
    },
}

当然现在调用它只是做 Animation.draw()

或者如果您想使用问题中没有的原型

var Animation = (function ()
    var Class = function()
    {
       this.draw = function () {};
       this.move = function () {};
    });
    (Class.prototype);
    return Class;
})();

如果您希望它作为实例方法工作,您也可以这样做

function Animation() {...}

Animation.prototype.move = function() {...};

Animation.prototype.draw = function() {...};

或使用 ES6

class Animation {

    constructor() {...}

    move() {
       ...
    }

    draw() {
       ...
    }
}

在您的代码中,draw & moveprivate 变量。

将您的功能分配给 this 的成员:

function Animation() {
  this.draw = function() {
      ...
  };

  this.move = function() {
    ...
  };
}

var an1 = new Animation();
an1.draw() // do something
an1.move() // also do something 

当然你也可以把它赋值给@UnicodeSnowman描述的原型。