Difference In declaring Javascript objects

gh9

I have been reading a few different Javascript authors and each has their preferred way to declare properties on objects. None of the authors really explains the difference between these different ways. What are the differences and which way is the preferred declaration to us?

var One = function() {
    var self = this;
    self.foo = function() {};
    return self;
}

var two = function() {
    foo: function() {}
};

var three = function() {
    var _foo = function() {};

    three.foo = _foo;
}
kemicofa ghost

tl;dr - See conclusion

Introduction

Declaring objects in javascript can be done many different ways, and from my point of view it all depends on how complex your project is.

The examples you proposed would be ways to declare variables within a complex project. You could even say for project maintainability and code quality the examples you proposed can be very interesting.

Part 1 - First example

Your first example you proposed was this function.

var One = function(){
   var self = this;
   self.foo = function(){};
   return self;
}

Context: Global -> One()

Suppose we don't create an instance of One (not using new) This function has two objectives.

  1. Attach the foo function to its parents context (usually window object = globally)
  2. Return foo function

You could say you're killing two birds with one stone. While doing two things at once can be interesting, in the end it could really become a context problem.

Context is pretty much asking yourself, what does this refer to? Non instantiated functions inherit the parents context which is fine if none of those parents are instantiated themselves. If this is the case (meaning this != window object) and your primary goal was to attach foo globally well it just won't work.

Context: Self -> new One()

If you call this function with new, this will be different. this will refer to an instance of One. This is a lot more logical way.

In the end you could say that an instance of One will feel almost like an object.

Comparing with objects

I say almost mainly because what is the difference if One was:

var One_object = {
  foo: function(){}
}

Well there isn't really, except you'll be more flexible with an object rather than an instance of a function.

//This will not work.
var a = new One();
a.titi = function(){
   alert('titi');
}

//This will work
One_object.titi = function(){
   alert('titi');
}

Improving the example

The only way that One as an instance can become interesting is if you declare multiple instances. Performance wise and memory wise it'll be more interesting.

var One = function(foo){
   //auto instantiate it's self
   if(!(this instanceof One)){
      return new One(foo);
   }
   this.foo = foo || function(){};
}

Creating multiple instances of One with the same function probably defeats the purpose, so here is an example of how you could improve One.

var a = One(function(){
    alert('instance one');
});

var b = One(function(){
    alert('instance two');
});

Part 2 - Second example

var two = function() {
    foo: function() {}l
};

Is actually wrong as I'm sure you've noticed from the comments. It should be instead:

var two = {
        foo: function() {}
    };

Where two is in fact an object and not a function.

This way of declaring variables/functions ensures that you are not overriding on a global scope any other function named "foo".

This can be very useful when you have a lot of js and you are declaring a lot of variables.

In this case, to access foo you need to simply call two.foo();

This is honestly my preferred way of declaring variables.

  1. Variables are not scattered all across the js file.
  2. They do not override any existing variables with the same name
  3. It's clean and maintainable.
  4. They can easily be moved around.

With this in mind, here is an example:

var options = {
  foo: function(){
    console.log('This is foo');
  },
  toto: function(){
    console.log('This is titi');
  }
};

var example = function(options){
  options.foo();
  options.toto();
}
example(options);

Part 3 - Barbaric

var three = function() {
    var _foo = function() {};

    three.foo = _foo;
}

A good standard when writing code is to keep the code readable. While this may work, it's not good practice. The main issue with writing Javascript is that it can easily become unreadable.. And in this case it feels barbaric (personal opinion).


Conclusion

As you've probably noticed example two is my preferred way (and to many others I know) in declaring Objects for the following reasons:

  1. Structured
  2. Organized
  3. Easy to handle
  4. Easy to maintain
  5. Flexibility
  6. No conflicts

Feel free to point out on anything I've missed.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

the different ways of declaring javascript objects - difference?

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

Javascript - Is there a difference between these two objects?

Array objects difference javascript angularjs

Difference between declaring variable

Difference in declaring strings in C

Declaring objects in the head of ViewController

Declaring a struct for json objects

performance of declaring objects

Getting difference between 2 arrays of objects in JavaScript

Find out difference and intersection in JavaScript array of objects

javascript group on an array of objects with timestamp range difference

Get the property of the difference between two objects in javascript

check the difference between two arrays of objects in javascript

How to compare two objects in javascript and get difference?

How to compare 2 objects in JavaScript and return difference

JavaScript - What is the difference between declaring a iteration variable using a let versus a var keyword inside a for-loop?

Difference between declaring properties in interface

Angular 2 declaring an array of objects

declaring multiple objects in one property

Declaring 2 similar anonymous objects

Declaring objects inside or outside function

Declaring multiple objects of same class?

What is the purpose of declaring objects with OR conditions?

Optimal way of declaring DI objects

Declaring functions in JavaScript

Declaring Multiple Variables in JavaScript

Declaring 'const' is not working in JavaScript