How to use object literal properties without being inside a function in javascript

I created an object literal in JS, but want to access a property without being in a function. Whenever I try, I get no results or return null .

JS:

 var settings = { prev: '#prev', next: '#next', slides: '#slides', crslContainer: '#carousel', //I'm trying to access the 'slides' by using 'this.slides' inDent: $(this.slides).find('li').outerWidth(), fx: 'rotate', myFunction: function () { console.log(settings.inDent); //This shows null in the console, why?? } } 

In the code above, I'm trying to access slides using this.slides , all inside the same object, but the console says null . But when I do this method, inDent: $('#slides').find('li').outerWidth() , then it works. Why is this? I suggested that this is the same as using these properties inside a function using the this , apparently this is not the case. I just want to pass the value of this property of the object, i.e. Strings, another property that is not a function.

Many thanks

+4
source share
3 answers

You cannot reference the "object defined" in the object literal. That is, there is no way to get an expression of a value for a property of an object of a substructure for the object itself, in order to access another (presumably, already defined) property.

However, you can add a property to an object after defining it.

  var obj = { a: 0 }; obj.b = (obj.a ? 1 : 2); 

Or in your case:

  var settings = { ... }; settings.inDent = ($(settings.slides).find('li').outerWidth()); 
+9
source

You need to use

 this.inDent 

The inDent field will be accessible through settings.inDent only outside the settings object definition

0
source

Use closure like

 var settings = function(){ var private = {}; private.slides = '#slides'; var public = {} public.inDent = ($(private.slides).find('li').outerWidth()); public.doSomething = function(){ console.log( public.inDent ); } return public; }(); 

The advantage of this is that it gives you "encapsulation" for free

By the way, you should not rely on anything publicly available, because maybe it can be changed, for example. settings.inDent = null , and then settings.doSomething() may not work correctly. What is the right way to do this:

 ... private.inDent = ($(settings.slides).find('li').outerWidth()); public.inDent = private.inDent; public.doSomething = function(){ console.log( private.inDent ); } 

i.e. make the inDent only inDent value (in a sense, that nothing outside the settings object can actually change the internal implementation of private.inDent ); as long as you always use private.inDent from settings , you will be safe, because even if someone does settings.inDent = null , settings.doSomething(); will function properly

0
source

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


All Articles