2

I'm trying to understand the fundamentals of object literals

window.Test = ({
    attribute1:'This is',
    attribute2:'a test',
    function1: function(){
        alert(this.attribute1 + ' ' + this.attribute2);
    }
});

//TEST 1
Test.function1(); // "This is a test"

//TEST 2
var tester = new Test(); //ERROR: Object is not a function
tester.function1();

If I understand correctly window.Test = creates a global variable in the window object. It would be the same as var Test = . Therefore it's logical that TEST1 works.

In TEST2 I try to instantiate the literal but this is not possible because it's a variable. I got the idea from Backbone.js where the following code does work:

window.Product = Backbone.Model.extend({});
var p = new Product();

I would expect Product to be a variable here as well, so no way to instantiate it.

Can anyone explain the difference between the Backbone example and my example? It seems I'm missing out on some fundamental understanding of literals.

Anonymoose
  • 2,389
  • 6
  • 36
  • 69

3 Answers3

3

First of all, this has nothing to do with JSON. That is a text format for representing objects. What you have is an object literal in Javascript. The JSON format is based on the Javascript syntax, but it's not the same thing.

You can't instantiate an object literal, because it is already an instance.

What the backbone extend method does is that it creates a function that will create an object. The extend method will return a function that you can use to create an instance because it will copy everything from the Model object into its own object.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

yes it is not a function, it is a js object and to clone it use this :

window.Test = ({
    attribute1:'This is',
    attribute2:'a test',
    function1: function(){
        alert(this.attribute1 + ' ' + this.attribute2);
    }
});

//TEST 1
Test.function1(); // "This is a test"

//TEST 2
var tester =  $.extend(true,{}, Test);
tester.function1();

Reference : here

Fiddle : here

Community
  • 1
  • 1
CME64
  • 1,673
  • 13
  • 24
1

object literals are already an instantiated object

var a = {}

is in this regard equivalent to:

var a = new Object()

so new {} is equivalent to new (new Object())

the new-keyword instantiates object from constructors. You can't instantiate something from an object that already is an instance.

Björn Roberg
  • 2,275
  • 2
  • 15
  • 15