Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to define a function?

I'm always learned to define a function in JavaScript like this:

function myFunction(arg1, arg2) { ... }

However, I was just reading Google's guide to Javascript, it mentioned I should define methods like this:

Foo.prototype.bar = function() { ... };

Question: Is "Foo" in the example an Object, or is it a namespace? Why isn't the Google example the following code (which doesn't work):

prototype.bar = function() { ... };

UPDATE: In case it helps to know, all of my JavaScript will be called by the users browser for my web-application.

like image 991
Timmy Avatar asked Jul 18 '10 03:07

Timmy


People also ask

What are the 3 ways we can define a function in JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.

What makes a good function?

A "good function" is: A pure function, one without side-effects whose return value depends only on its arguments. Available at a stable public name in a global namespace. Performs work only linearly proportional to the size of its arguments (considered as structures)

What are the steps followed by defining a function?

Steps to Writing a FunctionUnderstand the purpose of the function. Define the data that comes into the function from the caller (in the form of parameters)! Define what data variables are needed inside the function to accomplish its goal.


1 Answers

Your two examples are not functionally equivalent. The first example simply defines a function (probably a global one, unless you define it inside another function). The second example extends the prototype of a constructor. Think of it as adding a method to the class Foo.

Unless you're building a JavaScript library, my suggestion would be to use neither and use some kind of namespace system. Create a single global object that acts as a namespace through which you can access all your functions.

var MyObject = {
    utils: {
        someUtil: function() {},
        anotherUtil: function() {}
    },
    animation: {
        // A function that animates something?
        animate: function(element) {}
    }
};

Then:

// Assuming jQuery, but insert whatever library here
$('.someClass').click(function() {
    MyObject.animation.animate(this);
});

If you want to emulate classes in JavaScript, you would define the "class" as a function (the function itself being the constructor) and then add methods through the prototype property.

function Foo() {
    // This is the constructor--initialize any properties
    this.a = 5;
}
// Add methods to the newly defined "class"
Foo.prototype = {
    doSomething: function() { /*...*/ },
    doSomethingElse: function() { /*...*/ }
};

Then:

var bar = new Foo();
console.log(bar.a); // 5
bar.doSomething();
// etc...
like image 90
Sasha Chedygov Avatar answered Oct 05 '22 14:10

Sasha Chedygov