I always learn how to define a function in JavaScript like this:
function my Function (Arg1, arg2) {...} However, I was just reading, it mentions that I should define the methods like this:
Foo.prototype .bar = function () {...}; Question : Is the "Foo" example an object, or is it a namespace? Why Google Example is not the following code (which does not work):
prototype.bar = function () {...}; UPDATE : If it helps, then all my javascript will be called by the user browser for my web-application.
Your two examples are not functional equivalent The first example defines only functions (possibly a global one) , Unless you define it within any other function). The second example extends the prototype of a constructor, think about adding a method to class Foo .
Unless you are creating a Javascript library, my suggestion will not be to use or use any type of namespace system. Create a single global object that acts as a namespace through which you can use all your functions.
var MyObject = {utils: {someUtil: function () {}, second utility: function () {}}, animation: {// a function which animates something? Animate: function (element) {}}}; Then:
// Assume that the jQuery, but here's the library at $ ('. SomeClass'). Click (function () {MyObject.animation;) (this);}); If you want to emulate classes in javascript, you can define "class" as function (function is itself a constructor) and then prototype property. function fu () {// This is constructor - initializing any property to this.a = 5; } // Add methods to the new defined "class" Foo.prototype = {doSomething: function () {/*...*/}, doSomethingElse: function () {/*...*/}};
then:
var bar = new Foo (); Console.log (bar.a); // 5 times. They have some (); // etc ...
Comments
Post a Comment