Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...