ツ.jp
ツ.jp

Reputation: 315

Javascript Object Literal, Cannot Set Properties

I am trying to add elements to my object literal and all I receive are undefined outputs in the console.

Why is itemSize being printed as undefined and why, as a consequence, are all the properties I am trying to set also undefined. I must be missing something big here.

I also don't understand the purpose of get testFunction and how it is even accessed since it doesn't seem to be following the signature of other functions which have a colon after the function name.

I'm so confused at the moment.

index.html

var square = new GULE.Scene();
square.hey( 5 );

gule.js

 var GULE = GULE || {};

 GULE.Scene = function ( itemSize ) {

  this.itemSize = itemSize;
  console.log( "Trying in constructor: " + this.itemSize );
  console.log( "Passed variable: " + itemSize );

 };

 GULE.Scene.prototype = {

      constructor: GULE.Scene,
      stuff: 1,
      get testFunction () {
            console.log( "testFunction!" );
          },
      add: function () {
              this.stuff += 1;
            },
      hey: function () {
              console.log( this.stuff );
              console.log( "Trying in function: " + this.itemSize );
           }
 };

Upvotes: 0

Views: 198

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074008

Why is itemSize being printed as undefined...?

Because you're not passing anything into the Scene constructor, so the argument is undefined, which is what you're assigning to itemSize.

what is the purpose of the get testFunction...?

It creates a property called testFunction that, when accessed, calls a function; see §11.1.5 of the spec. It's an ES5 feature. If open your web console and then do this after creating your square:

var x = square.testFunction;

...you'll see "testFunction!" in the console, because you accessed the property.

The reason you see undefined when you read testFunction is that the function defined by the getter doesn't return anything.

Here's a clearer example:

(function() {
  "use strict";
  
  var obj = (function() {
    var propValue = "Initial value";
    
    return {
      normalProp: 42,
      get accessorProp() {
        display("Reading accessorProp");
        return propValue;
      },
      set accessorProp(value) {
        display("Writing accessorProp, new value: " + value);
        propValue = value;
      }
    };
  })();
  
  display("normalProp is " + obj.normalProp);
  display("accessorProp is " + obj.accessorProp);
  obj.accessorProp = "Testing";
  display("accessorProp is now " + obj.accessorProp);

  function display(msg) {
    var p = document.createElement("p");
    p.innerHTML = String(msg);
    document.body.appendChild(p);
  }
})();

Upvotes: 3

Abhishek Nafdey
Abhishek Nafdey

Reputation: 106

The right code should be - var square = new GULE.Scene(5); square.hey( );

Upvotes: 0

Related Questions