Jump to content

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


iwato

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

Link to comment
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
Link to comment
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
Link to comment
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
Link to comment
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...