Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Object-Oriented JavaScript Getters and Setters Object Interaction

Samuel Cleophas
Samuel Cleophas
12,348 Points

Why does the setter 'method' not take in arguments?

Why doesn't this code work? I feel like a lot of things are wrong.

class Owner {
    constructor (name, address) {
        this.address = address;
        this.name = name;
    }
    set mobile(phone) {
        this._mobile = phone.replace(/[^0-9]/g, '');
    }
    get mobile() {
        return this._mobile;
    }
}

const ernie = new Pet('dog', 1, 'pug', 'bark');
const owner = new Owner('Samuel', '18, Druitt Street');
owner.mobile.phone('(+61)447 21 4934');

console.log(ernie.owner.mobile);

After watching these videos, because the argument, property, and method are all named the same in the video, it just feels like I don't understand which one is which.

I named them differently to help myself understand what the heck is going on but I still don't get it. :(

3 Answers

Steven Parker
Steven Parker
218,654 Points

Since you renamed things, "phone" is not a property now, but "mobile" is. So to set and then get that property:

owner.mobile = '(+61)447 21 4934';

console.log(owner.mobile);

I also removed the line creating the constant "ernie" since "Pet" isn't defined here.

And setters are defined like methods, but to use them you make assignments as if they were variables.

Try

owner.mobile = '(+61)447 21 4934'; instead of owner.mobile.phone('(+61)447 21 4934');

console.log(owner.mobile);

Try this... const phoneNormalized = phone.replace(/[^0-9\.]+/g, '');