How to access external object using Javascript internal object function
I am researching keyword this
in Javascript. I am trying to access an external object with an internal 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 this doesn't work, but I don't know how to access the prop
external object.
source to share
It is generally a very bad idea for the internals of a function's property to 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 being used.
An alternative construct is the "model pattern" 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;
}
}
}
})();
source to share
You can use the link on outer
to access the details. 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.net/gk2fegte/2/
When you call this.prop
inside an inner object, it does not point to the outer, but to the object inner
. Check the test
function in the above code.
source to share
You are using a JavaScript object literal and functions, so the "this" context is different. More information on the "this" keyword can be found in How does the "his" keyword work inside a function? ... And in your case, use "external.prop" to access
source to share