var name = 'bob';
var someObject = {
name: 'james',
someProperty: {
name: 'sam',
getName: function() {
console.log(this);
return this.name;
}
}
}
var testing = someObject.someProperty.getName;
testing()
Window {external: Object, chrome: Object, customElements: undefined, originalOutline: undefined, someObject: Object…}
When I tried that, noticed how the result of my (this) was printed, and it refers to the global "this". This isn't what we want.
If I wanted to print "sam"
, I would do this to call it with a way to redefine what "this" means.
testing.bind(someObject.someProperty)(). // returns "sam"
In addition you can also do this:
var name = 'bob';
var someObject = {
name: 'james',
someProperty: {
name: 'sam',
getName: function() {
return this.name;
}.bind(someObject.someProperty)
}
}
var testing = someObject.someProperty.getName;
This will return "sam"
when you call it, regardless of the "this" context.
Another way of doing this is to keep your original code, but instead of setting
var testing = someObject.someProperty.getName;
instead change it to:
var testing = someObject.someProperty.getName();
This way now the object refers to the getName()
function using the context of your someProperty.