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,
Foo.__proto__ = Foo.prototype
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?
Here is a good example to demonstrate how Javascript works with static/instance variables and methods.
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
Call a static method from an instance:
Simple Javascript Class Project: https://github.com/reduardo7/sjsClass
You can achieve it as below:
You can now invoke "talk" function as below:
You can do this because in JavaScript, functions are objects as well. "zzzzBov" has answered it as well but it's a lengthy read.
When you try to call
Foo.talk
, the JS tries to search a functiontalk
through__proto__
and, of course, it can't be found.Foo.__proto__
isFunction.prototype
.In additions, now it is possible to do with
class
andstatic
will give