First, let's look at things you asked about which are not actually methods to make classes.
If you only need one object with methods, but no class, you can create an object literal.
var myObject = {
varname: value,
varname: value,
methodname: function() {
// do something
},
methodname: function() {
// do something
}
};
This is rarely useful, but it creates a single instance with its own variables, some of which are functions. Note that in JS, there is no difference between a property and a method. A method is just a property of type function
.
Variables created inside a function with the var
keyword are only available inside the function. People who make libraries often wrap their whole code in a closure in the form of a self-executing function, so that any temporary variables no longer exist at the end of the code:
(function(){
// code here
}());
Now to make a class in JS, you only need to create a constructor function. You can store properties in the created instance with the this
keyword.
function MyClass(param) {
this.value = param;
}
var instance = new MyClass("example");
A function is a block of code stored in an object. You can store functions inside variables like anything else, so you can also store functions inside objects.
function MyClass() {
this.myMethod = function() {
alert("hi");
};
}
But since all instances of your class will need to run the same code, it isn't efficient to create the function inside the constructor. That will make a new copy of the function for each instance you create. So instead of doing this, we store the function in the prototype of the object.
Whenever you type say, instance.someproperty
, the JS engine looks at instance
to see if it has a property called someproperty
. If it doesn't, it tries to look at instance
's prototype to see if it has a property of that name. And if it doesn't, it tries to look at that prototype's prototype... and so on, until it reaches the top of the chain.
So if you store the function in MyClass.prototype.myMethod
, you will be able to call it with instance.myMethod
and there will only be one copy of the function shared by all instances.
function MyClass(param) {
this.value = param;
}
MyClass.prototype.myMethod = function() {
alert(this.value);
};
There is one good reason to put functions inside the constructor instead of using the prototype chain: making pseudo-private variables and getter/setter functions. See more here.
As for how to name those two ways of binding methods to an object, functions declared inside the constructor are privileged methods while those declared with the prototype pattern are called public methods. You can use both on a single class.