0

I am trying to create my object through a function, but I am unable to figure out the syntax for the getter function.

var myObject = 
{
  0:123,

  get a()
  {
        return this[0];
  }
}


console.log("This works: " + myObject.a);


function test()
{
    this[0] = 123;

// error
    this.a = get function()
  {
  return this[0];
  };
}


var myTest = new test();

console.log(myTest.a);

Within the test function, the assignment of the get function throws a missing semicolon error and if I remove the keyword "function", it says that get is not defined.

How can I assign a getter function to the current object within my function?

2
  • I don't think the var f = get function(){...} syntax is correct, use var f=get {...} instead. Your function test fails to parse, while removing the function() makes it work Commented Feb 2, 2017 at 14:31
  • 1
    You get that error as that is not the correct syntax to use for defining a getter Commented Feb 2, 2017 at 14:34

2 Answers 2

2

You could try something like this:

var myObject = 
{
  0:123,

  get a()
  {
        return this[0];
  }
}


console.log("This works: " + myObject.a);


function test()
{
    this[0] = 123;

    Object.defineProperties(this, {"a": { get: function () { 
        return this[0]; 
    }}});   
}


var myTest = new test();

console.log(myTest.a);
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a shorthand version similar to what I was attempting to do or is this the only way?
I do not think so. You can only use the short way with an object literal. This is as close as i can get, and in this case, you are not passing back 'this'. function test() { return { "0":123, get a() { return this["0"]; } } }
0

Maybe this will work for you :

      function test()
      {
          this[0] = 123;

          Object.defineProperty(this, "a", { get: function () { return this[0]; } });
      }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.