JavaScript prototypes

Possible duplicate:
JavaScript: Class.method vs. Class.prototype.method

What is the difference between creating such a prototype:

Date.foo = function(bar) {
    alert(bar);
};

And this:

Date.prototype.foo = function(bar) {
    alert(bar);
};

Why / when should I use?

+3
source share
1 answer

in the first example, foo is a constructor method, its like a “static” method in java. Secondly, it’s like defining a foo method for a class - it is bound to an instance.

would you gain access to the first as

Date.foo()

and second -

Date d = new Date()
d.foo() 

or in another Date instance method, for example

this.foo()
+2
source

Source: https://habr.com/ru/post/1758120/


All Articles