I am learning about this
keyword in Javascript. I am trying a way to access an outer object property with the inner object function. For example :
var outer = {
prop : 'prop',
func : function(){
return this.prop;
},
inner : {
func : function(){
return this.prop;
}
}
}
--> outer.func() : 'prop'
--> outer.inner.func() : undefined
I understand why it doesn't work but I don't know how to access the prop
of the outer object.
By simply changing the names of "inner" variable to y and the "_inner" variable to z you will get your expected results.
You can bind the "outer" instance to the "inner" function by invoking the bind method on the inner function. Learn more at MDN. Or use an arrow function. I see you answered in 2016 so that should be an option.
Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .
It's usually a very bad idea to have the insides of a function property know anything about the variable name that has been assigned to the object that contains that property. It introduces unwanted dependencies and more importantly prevents more than one instance of such an object from existing.
An alternate construct is the "module pattern" show below, using a closure and a variable that allows any nested properties to access that (local) variable.
var outer = (function() {
var prop = 'prop';
return {
prop: prop,
func: function() {
return prop;
},
inner : {
func : function() {
return prop;
}
}
}
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With