我知道这是可行的:

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

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

但如果我想打电话

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

我找到了一些制作Foo的方法。谈工作,

Foo。__proto__ = Foo.prototype Foo。talk = Foo.prototype.talk

还有别的办法吗?我不知道这样做是否正确。在JavaScript代码中使用类方法还是静态方法?


当前回答

静态方法调用是直接在类上进行的,不能在类的实例上调用。静态方法经常用于 创建效用函数

非常清晰的描述

直接取自mozilla.org

Foo需要绑定到你的类 然后当你创建一个新实例时,你可以调用myNewInstance.foo() 如果你导入你的类,你可以调用一个静态方法

其他回答

当你尝试调用Foo时。JS尝试通过__proto__搜索函数talk,当然,它找不到。

Foo。__proto__是Function.prototype。

下面是一个很好的例子来演示Javascript如何处理静态/实例变量和方法。

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

静态方法调用是直接在类上进行的,不能在类的实例上调用。静态方法经常用于 创建效用函数

非常清晰的描述

直接取自mozilla.org

Foo需要绑定到你的类 然后当你创建一个新实例时,你可以调用myNewInstance.foo() 如果你导入你的类,你可以调用一个静态方法

如果你必须在ES5中编写静态方法,我找到了一个很棒的教程:

//Constructor
var Person = function (name, age){
//private properties
var priv = {};

//Public properties
this.name = name;
this.age = age;

//Public methods
this.sayHi = function(){
    alert('hello');
}
}


// A static method; this method only 
// exists on the class and doesn't exist  
// on child objects
Person.sayName = function() {
   alert("I am a Person object ;)");  
};

看到@https: / / abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/

你可以通过以下方式实现:

function Foo() {};

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

你现在可以调用"talk"函数如下:

Foo.talk();

您可以这样做,因为在JavaScript中,函数也是对象。