0

For the following syntax

    a = {
    get p() {
        alert(1)
    }
};
alert(a.p);

It prompts me 1, than undefined. For

a = {
    set p(x) {
        alert(x)
    }
};
alert(a.p);

It prompts me undefined.

I do not totally understand the behaviour, what does

a = {
    get p() {
        alert(1)
    }
}

and

a = {
    set p(x) {
        alert(x)
    }
};

mean?

2
  • The method p does not return any value, thats why the second alerts give you undefined Commented Dec 28, 2015 at 13:02
  • Does this answer your question? Getters \ setters for dummies Commented Jun 22, 2024 at 5:11

4 Answers 4

0

There are two types of object properties: data properties and accessor properties.
Accessor properties are accessed by getters and setters. Your object a is intended as object with accessor property which called p. Normally, such objects are declared in the following way:

a = {
    _p: 'my value', // intended as private
    get p() {
        return this._p;
    },
    set p(x) {
        this._p = x;
    }  
};

console.log(a.p);  // gives 'my value'
a.p = 'new value'; 
console.log(a.p);  // gives 'new value'

Another way is to use Object.defineProperty() method which lets you to set all needed properties attributes. Like this:

var a = {p: 'my value'};
    Object.defineProperty(a, 'p', {
      get: function() { return this.p; },
      set: function(newValue) { this.p = newValue; },
      enumerable: true,
      configurable: true
});
Sign up to request clarification or add additional context in comments.

Comments

0

because p() method returns nothing hence it returns undefined

if you do

a={get p(){alert(1); return 2;}};
alert(a.p);

it will alert 1 and then 2 since this p() method returned 2

Comments

0
{get p(){alert(1)}}

this is an object that has a getter p

when you use a.p it will use that getter to retrieve some value

so when you do alert(a.p); it first call the getter, so alert 1, then alert the returned value undefined.

Comments

0

[Edit] - You changed your original question so this answer doesn't cover everything.

p is a getter function - It is called whenever you access the p property. In your getter you have alert(1).

The getter function doesn't return anything. Thus, p is undefined. So the alert(a.p) alerts undefined.

Thus, your program does:

  • Get value of a.p: alert(a.p)
  • Calls p getter function. Which has alert(1)
  • p getter function returns nothing
  • Thus alert(a.p) alerts undefined

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.