Reputation: 2042
Does anyone know a more elegant way to be able to access parent's parent object inside a function?
var obj = {
subobj : {
func1 : function() {
// here 'this' will refer to window
// i want to access obj instead
}
}
};
var obj = {
func1 : function() {
// i know 'this' here will refer to bj
}
}
i also tried
var obj = {
subobj : {
func1 : function() {
// even 'this' will refer to window
}.bind(this)
}
}
but even in this bind example 'this' will refer to window because it is outside.
I CAN DO
var _this = obj;
inside func1 but i DON'T want to use this ugly trick.
I basically want to get obj context inside func1 OR add obj context to subobj. I can't think of anything right now, any suggestion from you guys?
THANKS
Upvotes: 0
Views: 70
Reputation: 45121
First of all. You don't really need to mess with the context since you already have obj
accessible from within your function func1
.
var obj = {
subobj : {
func1 : function() {
//use `obj` here
console.log(obj);
}
}
};
Or if you for some reason want to access obj as this. Do the following
var obj = {
subobj : {
func1 : function() {
//this is now obj here. Go suffer maintainer!
}.bind(obj);
}
};
Upvotes: 2