I agree that Functions are objects in JS. When using a Function as a constructor we can add properties to the object create by adding these properties to the prototype property on the function. This is what I tried:
var Mammal = function(name) {
this.name = name;
};
var Cat = function(name) {
this.saying = 'meow';
};
Cat.prototype = new Mammal();
Cat.prototype.display = function() {
console.log('I display Cats');
};
//This is what I find hard to digest
Cat.display = function() {
console.log('I display cats but at the top level');
};
What I find hard to grasp is the commented portion. I was just trying to picture what goes where and this particular part I don’t understand. I mean if I had to write a function and do something like this while defining the function what would be the syntax like?
If I try something like the following:
function demo() {
this.saying = function() {
console.log('I display cats but at the top level');
};
};
The variable this here refers to the DOMWindow. How do I achieve the above thing within a function definition.
I am a total newbie to JS. I apologize for any ignorance on my part.
Those are analogous to static methods in class based objects. That is, the method can only be accessed from the constructor, not from the instance itself.
A good example of this ìs jQuery.get() You can’t do
You have to use
However, if you do need to access the static method from an instance, you have two options
http://jsfiddle.net/c39bW/
Not that your constructor property for Cat is broken, when you setup inheritance, you should fix the Cat.prototype.constructor to point back to Cat, see my jsFiddle above. Also, you’re not calling the base constructor (Mammal) from Cat’s constructor. For a tutorial on the minimal requirements for inheritance, see http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html
A good example as to when static properties are useful is when an object needs to keep track of how many times it has been instantiated, you can’t do that at an instance level;