Calling an object method from an object property definition

I am trying to call an object method from a property definition of an object (of the same object) to no avail.

var objectName = { method : function() { return "boop"; }, property : this.method() }; 

In this example, I want to assign the return value of objectName.method ("boop") to the object Name.property.

I tried objectName.method() , method() , window.objectName.method() , along with options for noting the brackets of all of these, for example. this["method"] , with no luck.

+4
source share
6 answers

When initializing this , this does not apply to the object containing the method property (which has not yet been initialized), but to the current context - and since it does not have the method property, you get a TypeError.

If this is the custom getter you want, you can look at the use of getters and setters in javascript - they are not supported by ECMAscript until ES5, but many engines support them nonetheless .

+5
source

I see no reason why you want to do this?

Why not just use getter if you don't want to use the method name.

 var objectName = { method : function() { return "boop"; }, property : function () { return this.method(); } }; 
+1
source
 /* overwrites the `property` function with a the set value * the first time it called. From then on it just a * property */ var objectName = { method: function(){ return 'boo'; }, property: function(){ var returnValue = this.method(); this.property = returnValue; return returnValue; } }; /* or */ var objectName = { property: ( function(){ return 'boo'; }() ); }; /* this evaluates the anonymous function within * the parenthetical BEFORE the definition of * objectName leaving only the returned value * to be set to property */ /* or */ var objectName = { method: function(){ this.property = 'boop'; return this.property; } } /* calling the method to create/set the property * for objectName to the evaluated value */ /* or */ var objectName = { data: { property: 'boop' }, property: function( value ){ if ( value ) this.data.property = value; return this.data.property; } }; /* the last one, I believe, is a neat way of handling * both set and get stealing the concept from my use * with JQuery. * set = objectName.property( 'boo' ); * get = objectName.property(); */ 
0
source

Another way to do this:

 var objectName = { method : function() { return "boop"; } }; $.extend(objectName, { property : objectName.method() }) 

objectName is already initialized during a method call.

0
source

It worked for me as follows:

 var objectName = { method : function() { return "boop"; }, property : objectName.method() }; 
0
source

Could you just go:

 var objectName = { method : function() { return "boop"; }, property : function() { return this.method(); } }; 
-1
source

Source: https://habr.com/ru/post/1333961/


All Articles