我知道这是可行的:
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代码中使用类方法还是静态方法?
在你的例子中,如果你想要Foo.talk():
function Foo() {};
// But use Foo.talk would be inefficient
Foo.talk = function () {
alert('hello~\n');
};
Foo.talk(); // 'hello~\n'
但这是一种低效的实现方式,使用原型更好。
另一种方式,My way定义为静态类:
var Foo = new function() {
this.talk = function () {
alert('hello~\n');
};
};
Foo.talk(); // 'hello~\n'
上面的静态类不需要使用原型,因为它只会被构造一次作为静态使用。
https://github.com/yidas/js-design-patterns/tree/master/class
下面是一个很好的例子来演示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
如果你必须在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/