Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Functions and Objects

Tags:

javascript

I am learning Javascript, I have been using PHP for about 10 years so I have some knowledge of Javascript, mostly just using jQuery and hacking it together, I think it's time I put some effort into learning it better so I have been reading up on it.

Below are my examples of defining and calling some functions.

Method 1

function testFunction1() {
    console.log('TestFunction1() was ran');
}
testFunction1();

Method 2

var testFunction2 = function() {
    console.log('TestFunction2() was ran');
}
testFunction2();

Method 3

var TestFunction3 = {
    flag: function() {
        console.log('TestFunction3.flag() was ran');
    },
    unflag: function() {
        console.log('TestFunction3.unflag() was ran');
    }
};
TestFunction3.flag();
TestFunction3.unflag();

Method 4

var TestFunction4 = {
    Like: {
        comment: function() {
            console.log('TestFunction4.Like.comment() was ran');
        },
        user: function() {
            console.log('TestFunction4.Like.user() was ran');
        }
    },
    Unlike: {
        comment: function() {
            console.log('TestFunction4.Unlike.comment() was ran');
        },
        user: function() {
            console.log('TestFunction4.Unlike.user() was ran');
        }
    }
};
TestFunction4.Like.comment();
TestFunction4.Like.user();
TestFunction4.Unlike.comment();
TestFunction4.Unlike.user();

Ok so I understand method 1 and 2 to be just a basic function call.

1)
Method 3 and 4 are where my questions start, from other post and from reading, I cannot tell if these are still considered a basic function with namespacing applied, or if these would be considered Objects?

2)
I have seen where sometimes an object would be called with the new word however running all this in the browser works fine so I am guessing this is not an object? If it is not an object, how would I make it into an object?

3)
Example 3 and 4 are pretty much the same with the exception that example 4 has functions defined 1 level deeper then example 3, is there a name for example 3 and 4 or are they considered the same thing?

4)
Lastly of all the 4 examples, is any of these 4 methods preferred over the other?

Sorry for all the questions in 1 but they are all related and I don't think I need to start 4 separate questions for this.

like image 841
JasonDavis Avatar asked Nov 28 '11 23:11

JasonDavis


People also ask

IS function and object same in JavaScript?

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

What are functions and objects?

An object is a collection of functions and data. A function is a collection of commands and data. When a bunch of functions work together to perform a certain task we may call this community of functionality an object.

What are functions in JavaScript?

A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.

What are the 3 types of functions in JavaScript?

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


2 Answers

3 is an object. It has object properties, which themselves have properties that are functions. 4 is the same idea, just with less nesting.

As far as using the new keyword, that's just one way to create objects. When a function is called with new, that's called constructor invocation. It's one of the four ways functions can be invoked. The other three, for completeness, are method invocation, function invocation, and apply invocation.

If you want to use a function as a constructor you would, by convention, start it with a capital letter, then call it with the new keyword. This creates a blank object based on Object.prototype, and sets it equal to this. When using this mode of object creation you'd add properties to your resulting object by adding them directly to this, ie this.foo = 12

Methods of that object would be added by modifying the prototype of your function.

YourConstrutor.prototype.newMethod = function() {
   alert(this.foo);
};

Note that using constructors comes with a lot of difficulties, especially if you want to implement inheritance

Objects can be created more simply by returning them from a "regular" function:

function createCar() {
   return {
      prop1 : 12,
      someFunc: function() {
         alert(this.prop1);
      }
   }
}

This also make information hiding easy:

function createCar() {
   var protectedInfo = "haha I'm protected"; ///not visible outside this function
   return {
      prop1 : 12,
      showProtectedData: function() {
         alert(protectedInfo);
      },
      someFunc: function() {
         alert(this.prop1);
      }
   }
}

(you can implement information hiding with constructors too, but protected info will not be visible to methods you put on the prototype; protected information will only be visible to methods you add manually to this)

The only disadvantage here is that creation will be slightly slower, since it's creating that someFunc method de novo each time; with a constructor it would exist once, as part of the prototype.

4. Which is preferable? If you just want to create a single object, then use 3 or 4. Simple.

If you want to repeatedly create an object, then it depends. Will you be creating tens of thousands of these objects, such that speed is of the utmost importance? If so, you'll probably want a constructor. If not, then it depends on what your most comfortable with. I find a simple function that returns an object most clear, and most flexible, but that's just my preference. Many developers far smarter than me prefer constructors.

like image 93
Adam Rackis Avatar answered Oct 14 '22 11:10

Adam Rackis


  1. 3 and 4 are still functions, but they're also objects. 1 and 2 are also objects as well as being functions. All functions are objects - JavaScript has first-class functions.

  2. It instantiates an object. The functions being called with new are constructors. They create objects.

  3. They're the exact same thing. Like in #1, nesting level has no effect on the type of anything...

  4. No, because they're all equivalent. A Function is an Object and it doesn't matter where it is. Generally, though, you would avoid heavy nesting for the purpose of namespaces because it can slow your code down, without all that much clarity benefit. JavaScript wasn't really designed with namespaces in mind.

like image 25
Ry- Avatar answered Oct 14 '22 13:10

Ry-