Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object definition techniques, pros and cons

What are the basic ways of defining reusable objects in Javascript? I say reusable to exclude singleton techniques, such as declaring a variable with object literal notation directly. I saw somewhere that Crockford defines four such ways in his book(s) but I would rather not have to buy a book for this short bit of information.

Here are the ways I'm familiar with:

  • Using this, and constructing with new (I think this is called classical?)

    function Foo() {
        var private = 3;
        this.add = function(bar) { return private + bar; }
    }
    
    var myFoo = new Foo();
    
  • Using prototypes, which is similar

    function Foo() {
        var private = 3;
    }
    Foo.prototype.add = function(bar) { /* can't access private, correct? */ }
    
  • Returning a literal, not using this or new

    function Foo() {
        var private = 3;
        var add = function(bar) { return private + bar; }
        return {
            add: add
        };
    }
    
    var myFoo = Foo();
    

I can think of relatively minor variations on these that probably don't matter in any significant way. What styles am I missing? More importantly, what are the pros and cons of each? Is there a recommended one to stick to, or is it a matter of preference and a holy war?

like image 813
Tesserex Avatar asked Jun 01 '11 03:06

Tesserex


People also ask

What is the advantages of using object literals?

Advantage of Object LiteralIt provides a shorter syntax for creating/initializing properties from variables (Property Shorthand). It provides a shorter syntax for defining function methods. It enables the ability to have computed property names in an object's literal definition.

What is an object JavaScript?

In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc. The same way, JavaScript objects can have properties, which define their characteristics.

Why are JavaScript objects important?

Although objects are a very important part of this programming language, they are not the only thing that keeps it together or allows programmers to interact with the code. Primitives are another important part of the JavaScript language. In contrast to objects, they are data that is immutable and cannot be changed.


2 Answers

Use the prototype. Returning specific objects from constructors makes them non-constructors, and assigning methods to this makes inheritance less convenient.

Returning an object literal

Pros:

  • If a person forgets new, they still get the object.

  • You can create truly private variables, since all methods of the object defined inside the constructor share its scope.

Cons:

  • It’s not a real constructor. Adding something to its prototype won’t change the returned objects, new or no new. new Foo() instanceof Foo would also result in false.

Using prototype

Pros:

  • You leave the constructor uncluttered.

  • This is the standard way of doing things in JavaScript, and all built-in constructors put their methods on their prototypes.

  • Inheritance becomes easier and more correct; you can (and should) use Object.create(ParentConstructor.prototype) instead of new ParentConstructor(), then call ParentConstructor from within Constructor. If you want to override a method, you’re able to do it on the prototype.

  • You can “modify” objects after they’ve already been created.

  • You can extend the prototypes of constructors you don’t have access to.

Cons:

  • It can get to be a bit too verbose, and if you want to change the function’s name, you have to change all of the functions added to the prototype, too. (Either that or define the prototype as one big object literal with a compatible property descriptor for constructor.)

  • They don’t share an instance-specific scope, so you can’t really have private variables.

Assigning to this.* in the constructor

Pros:

  • You can use closures and therefore private member variables.

Cons:

  • No duck typing; you can’t call a method right off of the prototype with any old object. For example, Array.prototype.slice.call(collectionLikeObject).
like image 172
Ry- Avatar answered Oct 17 '22 06:10

Ry-


It's mostly a matter of preference. There's no one way to make Chicken Noodle soup, and uniform objects are the same way.

I don't use any of those 3, although they all work for their own purposes. I use a custom function called Object:deploy, and use it like this..

var a = { hey: 'hello' },
    b = {}.deploy(a);

console.log(b.hey); // 'hello'

Using prototype is the best for most people because of automatic trickling.

function A() {};
A.prototype.hello = "Hey";

var a = new A();
console.log(a.hello); // 'Hey'

A.prototype.hello = "Hello";

console.log(a.hello); // 'Hello'

And contrary to popular belief, you can use private variables in prototype.

function Hello() {};

(function () {
    var greeting = "Hello";

    Hello.prototype.greet = function () { return greeting };
}).apply(this);

But even though that's possible, it's usually better to do..

function Hello() {};
Hello.prototype.greeting = "Hello";
Hello.prototype.greet = function () { return this.greeting };
like image 39
McKayla Avatar answered Oct 17 '22 06:10

McKayla