Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object literal vs constructor+prototype

Object literal=name value pairs wrapped in curly braces.

Constructor=a function used to create multiple instance using keyword new.

Prototype=for extension of a literal.

This is what I have understood till now.But the more I research,More I get confused about what is the significance of each one of them. I have used constructor,protoypes and literals in my code a few times.But everytime I use them,I feel like I am still not aware of the full potential of it.I want to go one step ahead of being a begineer now.I hope Folks at stackoverflow help me achieve it

  1. Which is the best preferred way of programming(object literals vs constructors vs prototype)

  2. can a code with constructor and protoype be written using just object literals without using constructor and protoype.

  3. what is the signifiance of anonymous function.

A very simple example demonstrating their importance will also do.I am aware of what they are but I am not aware of what possible magic they can do.

like image 370
HIRA THAKUR Avatar asked Jun 23 '13 12:06

HIRA THAKUR


People also ask

Do object literals have prototype?

The object literals are using undefined and number 15 to setup __proto__ value. Because only an object or null are allowed to be prototypes, objUndefined and objNumber still have their default prototypes: plain JavaScript objects {} .

What is the difference between constructor and prototype?

So what's the difference between constructor and prototype? A short answer is that the constructor is a function that is used to create an object, while the prototype is an object that contains properties and methods that are inherited by objects created from a constructor.

What is the difference between an object and an object literal?

Objects created using object literal are singletons, this means when a change is made to the object, it affects the object entire the script. Whereas if an object is created using constructor function and a change is made to it, that change won't affect the object throughout the script.

What is a constructor prototype?

constructor. The constructor property returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name.


1 Answers

There is a (fundamental, in my opinion) difference between object literals and functions, the "private" variables. Since an object can't be instantiated(because it is already an instance of Object) it has no possibility to have its own (new) scope. It is a base concept of advanced JS programming. Having a new scope allows you to do almost everything(you can declare your own window, document or whatever you want except the JS keywords inside your own scope). Now, some simple examples:

Let's assume you want to create a large number of instances of the same object(using as few lines as possible):

function MyObj(i) {     var privateCounter = "I am the instantiated object " + i + " .";     this.counter = function() {         return privateCounter;     }; }  var MyObjList = [],     ObjLitList = []; for (var i = 0; i < 100; i++) {     MyObjList.push(new MyObj(i));     ObjLitList.push({counter: "I am the literal object number " + i + "."}); } 

Now you have 200 objects that are almost, but not precisely, the same thing. You can extend them as you prefer, because functions are objects, but in the case of the function you cannot access the private variable directly. Let's see which are the advantages of a function:

  • It is treated like an Object
  • It has its own Prototype
  • It has private variables

And the Objects?

  • It is an Object
  • It doesn't have its own Prototype, but you can declare the functions and extend the object itself
  • It doesn't have private variables

Apart the private vars, they are not much different from each other.

Let's see what a function's prototype can do:

MyObj.prototype.setX = function(x) {     this.x = x; } 

Using the prototype allows you to create an only instance of an anonymous function(which can be named too and then assigned) which will be shared across instances. How can you do the same thing with object literals?

function setX(x) {     this.x = x; } var obj = {     setX: setX }; 

As you can see you have to create the object defining everytime a property which is setX. Otherwise, you can extend Object.prototype itself(but there is a long debate about extending the prototype of native JS objects).

So which is the best way? There is no one, it depends on what you have to do, what you need from your script, which of the two you feel more comfortable with.

I prefer writing my own functions and treat them like classes, because they are more readable and I am able to use "private" variables. I don't know anyone using literals instead of functions though.

As for the questions:

Which is the best preferred way of programming(object literals vs constructors vs prototype)

Answered.

can a code with constructor and protoype be written using just object literals without using constructor and protoype.

Yes, you can if you don't need private variables(and if the script isn't too big. Imagine jQuery written as an Object literal :D).

what is the signifiance of anonymous function.

Oh well, I can answer with an example:

//code myNamedFunction(); //code function myNamedFunction() {     alert("I'm defined everywhere! :)"); } 

This works and won't generate a TypeError.

myAnonymousFunction(); var myAnonymousFunction = function() {     alert("I'm defined after this declaration :("); } myAnonymousFunction(); // works! 

This will cause a Uncaught TypeError: undefined is not a function, because myAnonymousFunction is only a reference to the effective function(which is unnamed, so it is not callable from the script).

There are a lot of things to say about this argument, and a good point to start advanced programming is Javascript Garden. Other good readings are Basics of OOP in JS - NetTutsPlus, Working with Objects - MDN and OOP in JS - Phrogz

Hope this helps!

Sidenote: functions also have a good advantage since they can change their context(this) just with a function(call for example), while objects can't.

like image 193
Niccolò Campolungo Avatar answered Oct 14 '22 12:10

Niccolò Campolungo