Class vs. static method in JavaScript

2019-01-02 19:08发布

I know this will work:

function Foo() {};
Foo.prototype.talk = function () {
    alert('hello~\n');
};

var a = new Foo;
a.talk(); // 'hello~\n'

But if I want to call

Foo.talk() // this will not work
Foo.prototype.talk() // this works correctly

I find some methods to make Foo.talk work,

  1. Foo.__proto__ = Foo.prototype
  2. Foo.talk = Foo.prototype.talk

Is there some other ways to do this? I don’t know whether it is right to do so. Do you use class methods or static methods in your JavaScript code?

13条回答
流年柔荑漫光年
2楼-- · 2019-01-02 19:57

I use namespaces:

var Foo = {
     element: document.getElementById("id-here"),

     Talk: function(message) {
            alert("talking..." + message);
     },

     ChangeElement: function() {
            this.element.style.color = "red";
     }
};

And to use it:

Foo.Talk("Testing");

Or

Foo.ChangeElement();
查看更多
登录 后发表回答