OOP Javascript parent object method or object?

var O = { elements: { main: function() { return jQuery("#main"); }, footer: function() { return jQuery("#footer"); } }, main: function(html) { return (this.elements.main()); }, style: { setMaincolor: function() { // TypeError: Cannot call method 'main' of undefined return (this.elements.main()); } } }; 

So; I'm O.style Object Parents Objects ????

 O.style.setMaincolor() // TypeError: Cannot call method 'main' of undefined O.main() // [<div id=​"main">​</div>​] 

The setMaincolor method returns this in O Object

+4
source share
4 answers

this refers to the object on which the method was called.

main() is called on the O object, so this is a reference to O Therefore this.elements === O.elements .

setMaincolor() is called in the style object, so this will be a reference to O.style , which does not have the .elements property.

+3
source

You must explicitly define what this should mean; if not specified, this will point to the nearest object.

You can create a closure for it as follows:

 var O = (function() { var self = { elements: { main: function() { return jQuery("#main"); }, footer: function() { return jQuery("#footer"); } } } self.style = { setMaincolor: function() { return self.elements.main(); } } return self; }()); 

(function() { ... }()); returns an object, and self is the "private" variable, which only the O object knows about, and points to itself, thereby doing the reference work .elements.main() .

+1
source

since the setMaincolor method setMaincolor defined in the style object, this refers to the style object. Since the style object does not have the elements property, this.elements is undefined.

One solution would be if you name the object O explicitly, instead of using this :

 var O = { elements: { main: function() { return jQuery("#main"); }, footer: function() { return jQuery("#footer"); } }, main: function(html) { return (this.elements.main()); }, style: { setMaincolor: function() { // TypeError: Cannot call method 'main' of undefined return (O.elements.main()); } } }; 
+1
source

You cannot reference this.elements in the setMaincolor method. this -pointer refers to your object style: use O.elements.main() in your O.style.setMaincolor function.

 style: { setMaincolor: function() { return (O.elements.main()); } } 

Although, I do not recommend this approach, note that you can also use: O.style.setMaincolor.call(O,[]); which makes this O link.

Here is how I would solve it:

 var O = (function() { var self = { elements: { main: function() { return jQuery("#main"); }, footer: function() { return jQuery("#footer"); } }, main: function(html) { return self.elements.main(); }, style: { setMaincolor: function() { return self.elements.main(); } } }; return self; }()); 
0
source

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


All Articles