iwato Posted July 24, 2019 Share Posted July 24, 2019 jsonLikeObj.getFoo.value( ); BACKGROUND: Consider the following object var jsonLikeObj = Object.create( {}, {getFoo: { value: function() { return this.foo = 1; }, enumerable: false } } ); DISCUSSION: Now I could more easily understand the following that does not work, than what does work. What Does Not Work jsonLikeObj.getFoo.value(); What Does Work jsonLikeObj.getFoo(); QUESTION: What is going on? Roddy Link to comment Share on other sites More sharing options...
justsomeguy Posted July 24, 2019 Share Posted July 24, 2019 It sounds like you think your code is the same as this: var jsonLikeObj = { getFoo: { value: function() { return this.foo = 1; }, enumerable: false } }; It's not, that's not what Object.create does. That second parameter is a description about how to create the object, it's not the actual object. jsonLikeObj.getFoo.enumerable is also undefined. Why? Because that's not the actual object, it's the specification for the object. It's metadata. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create 1 Link to comment Share on other sites More sharing options...
Ingolme Posted July 24, 2019 Share Posted July 24, 2019 The second argument of the Object.create() method contains property definitions which follow a specific format. In your code, the definition of getFoo is saying that its value is a function and that it is enumerable. You can see all of the different features that a definition can have here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties#Parameters If you want your code to behave as you predicted, just drop the Object.create() method and assign the object directly: var jsonLinkObj = { getFoo: { value: function() { return this.foo = 1; }, enumerable: false } }; The purpose of Object.create() is mainly for copying existing objects, if you are just creating a new one you probably don't need it. 1 Link to comment Share on other sites More sharing options...
iwato Posted July 25, 2019 Author Share Posted July 25, 2019 OK. I get it.! The properties value and enumerable are property descriptors. They define the nature of the property getFoo. Thanks! Roddy 1 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now