我知道这是可行的:
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代码中使用类方法还是静态方法?
如果你必须在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/