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:33

Here is a good example to demonstrate how Javascript works with static/instance variables and methods.

function Animal(name) {
    Animal.count = Animal.count+1||1;// static variables, use function name "Animal"
    this.name = name; //instance variable, using "this"
}

Animal.showCount = function () {//static method
    alert(Animal.count)
}

Animal.prototype.showName=function(){//instance method
    alert(this.name);
}

var mouse = new Animal("Mickey");
var elephant = new Animal("Haddoop");

Animal.showCount();  // static method, count=2
mouse.showName();//instance method, alert "Mickey"
mouse.showCount();//Error!! mouse.showCount is not a function, which is different from  Java
查看更多
刘海飞了
3楼-- · 2019-01-02 19:36

Static method calls are made directly on the class and are not callable on instances of the class. Static methods are often used to create utility function

Pretty clear description

Taken Directly from mozilla.org

Foo needs to be bound to your class Then when you create a new instance you can call myNewInstance.foo() If you import your class you can call a static method

查看更多
长期被迫恋爱
4楼-- · 2019-01-02 19:40

Call a static method from an instance:

function Clazz() {};
Clazz.staticMethod = function() {
    alert('STATIC!!!');
};

Clazz.prototype.func = function() {
    this.constructor.staticMethod();
}

var obj = new Clazz();
obj.func(); // <- Alert's "STATIC!!!"

Simple Javascript Class Project: https://github.com/reduardo7/sjsClass

查看更多
伤终究还是伤i
5楼-- · 2019-01-02 19:41

You can achieve it as below:

function Foo() {};

Foo.talk = function() { alert('I am talking.'); };

You can now invoke "talk" function as below:

Foo.talk();

You can do this because in JavaScript, functions are objects as well. "zzzzBov" has answered it as well but it's a lengthy read.

查看更多
孤独总比滥情好
6楼-- · 2019-01-02 19:41

When you try to call Foo.talk, the JS tries to search a function talk through __proto__ and, of course, it can't be found.

Foo.__proto__ is Function.prototype.

查看更多
梦醉为红颜
7楼-- · 2019-01-02 19:46

In additions, now it is possible to do with class and static

'use strict'

class Foo {
 static talk() {
     console.log('talk')
 };

 speak() {
     console.log('speak')
 };

};

will give

var a = new Foo();
Foo.talk();  // 'talk'
a.talk();    // err 'is not a function'
a.speak();   // 'speak'
Foo.speak(); // err 'is not a function'
查看更多
登录 后发表回答