Reputation: 93
I just started learning Javascript about a week ago and I have run in to a bit of a stumbling block. In the link provided, I for whatever reason cannot call the function inside the object. Any ideas what I am doing wrong? Any advice would be great.
Upvotes: 0
Views: 1131
Reputation: 1055
Because the scope has changed.
In JavaScript, scope refers to the current context of your code. Scopes can be globally or locally defined. Understanding JavaScript scope is key to writing bulletproof code and being a better developer. You’ll understand where variables/functions are accessible, be able to change the scope of your code’s context and be able to write faster and more maintainable code, as well as debug much faster.
So the correct code is:
var that = this;
var testObject = { bar: function() { return that.word }}
In your solution, "this" is "window" object. So you also can code this:
var testObject = { bar: function() { return window.word }}
Upvotes: 0
Reputation: 6803
var testObj = {
bar: function(){
console.log(this.word)
}
}
When you call testObj.bar Here this refers to the testObj and testObj has no property word
var testObj = {
bar: function(){
console.log(this.word)
}.bind(this)
}
Use .bind(this) or .bind(window)
Upvotes: 0
Reputation: 284
You are calling the function, but the function is returning undefined. Be aware of the fact that this
has different meanings called in different context, in testObj
, this == testObj
, hence this.word
is undefined.
Maybe this fiddle can help.
Upvotes: 2