Jump to content
iwato

Understanding Anonymous Functions as the Value of an Object's Property-Value Pairs

Recommended Posts

 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

Share this post


Link to post
Share on other sites

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

  • Thanks 1

Share this post


Link to post
Share on other sites

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.

  • Thanks 1

Share this post


Link to post
Share on other sites

OK.  I get it.!

The properties value and enumerable are property descriptors.  They define the nature of the property getFoo.

Thanks!

Roddy

  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...