Because your Person Constructor produces an object with no properties whatsoever.

Code:

function Person(firstName) {
var _firstName = firstName;
};

var p = new Person("John");

console.log(p); //produces '{}' --> an empty object

If you rewrite it as:

Code:

function Person(firstName) {
this._firstName = firstName;
};

var p = new Person("John");

console.log(p); //produces --> { _firstName: 'John' }

03-03-2014, 10:47 PM

grendall

Thanks for responding, Tcobb.

I guess I didn't phrase my question correctly, my apologies. I knew the 'p' instance had no properties. But if you look at my code, I did use Object.defineProperty to create a getter/setter, which didn't seem to take any effect, and that was what puzzled me.

I declared _firstName the way I did to make it private, and I wanted the getter/setter to be the sole public methods. Do you see any reason why the Object.defineProperty didn't have any effect?

03-03-2014, 11:59 PM

Tcobb

Sorry --post deleted. The stuff I sent before was wrong in part.

The problem is that your Person constructor object, as written, doesn't retain the value of John. You have to use the setter you created to place the value in there first.

03-04-2014, 01:02 AM

Tcobb

Once again--my apologies for the last post. I was and am tired. What I said above was true, but the more fundamental problem is that Object.defineProperty requires that you send an object as the first argument. What you are doing is sending the Person constructor, a FUNCTION as the argument.

The examples you showed me somehow does only the second. Is there a way to create a class that can do BOTH of the above and have firstName defined as a getter and setter internally?

I'm also trying to just make an object with the capability of having private and public properties and methods. Once I can do that, I'm done with this part and I'm moving on, but I can't seem to accomplish this seemingly simple goal.

Do you think you can show me a code snippet to make an object that meets the criteria I'm striving for? I don't think it will be exceedingly long. Thanks.