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.
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.
- Please see my ment to @connexo and then please elaborate on why you want to do this. – Alnitak Commented Jun 7, 2015 at 16:07
- Because I have a function which has an argument which is an outer object without name, and there is an inner object which want to access one function of the outer . I am wondering if there is anyway to access it without calling the outer object's name. :) I see there is no way now. Thanks for your advice @Alnitak. – Phi Nguyen Commented Jun 7, 2015 at 16:29
4 Answers
Reset to default 10It'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;
}
}
}
})();
var outer = {
prop : 'prop',
func : function(){
return this.prop;
},
inner : {
func : function(){
return outer.prop;
}
}
}
You can use a reference to outer
to access props. For example:
var outer = {
prop : 'prop',
test : function() {
return this === outer;
},
func : function(){
return this.prop;
},
inner : {
func : function(){
return outer.prop;
},
test: function() {
return this === outer;
}
}
}
console.log(outer.func()) // prop
console.log(outer.test()) // true
console.log(outer.inner.func()) // prop
console.log(outer.inner.test()) // false
https://jsfiddle/gk2fegte/2/
When you call this.prop
within the inner object this doesn't point to outer but to the inner
object. Check out the test
function in the above code.
You are using the JavaScript object literal and functions, so that the context of "this" keyword differs. You can see more details about the "this" keyword in How does "this" keyword work within a function?. And in your case, use "outer.prop" to access