Reputation: 83
I have an object called clock.
I have a method of said object called time.
If I used this.propertyName inside my time method, this will give the property to my clock object, right? But what if there is an if/else statement (within the time method itself), for example, which needs to run before the value of the property can be assigned?
if(t.getHours() >= 12){
this.ap = "AM";
}else{
this.ap = "PM";
}
So, if I used a simple value like this.ap = "hi", this works fine. It gives the property to my object. If I have a statement like shown above, the property is undefined. What is the best way around this?
Also, another quick question since I'm only just starting to use my own objects. If I have an object with 3 separate methods, and I want to use a value in ALL methods that's been declared within 1 method, assigning it as a property of my object allows me to do this. Am I right?
So If I used var property = "" in one method, the only way to access this in my other methods is to return it. But setting the property to the object solves this? I realize I can experiment around with this but I'd rather just know the proper way.
Edit: Here's an example. Obviously I'm misunderstanding something. I can't seem to define properties from within a method.
var clock = {};
clock.test1 = "test 1.";
clock.time = function(){
clock.test = "test 2.";
if(t.getHours() >= 12){
clock.ap = "PM";
}else{
clock.ap = "AM";
}
}
alert(clock.test1); //success
alert(clock.test); //returns undefined
alert(clock.ap); //returns undefined
Upvotes: -1
Views: 48
Reputation: 45145
The usual way to avoid problems with binding this
is to do something like this:
var MyObject = function() {
var self = this;
self.someProperty = "foo";
self.someMethod() {
self.someProperty = "bar";
}
}
var anInstance = new MyObject();
console.log(anInstance.someProperty); // foo
anInstance.someMethod();
console.log(anInstance.someProperty); // bar
This avoids problems with this
being something other than what you expected it to be, which can happen depending on how you call methods (using a method as a handler for some DOM event for example).
This example works by exploiting closure
, which is a very important concept in Javascript that you should read up on (Google it).
Upvotes: 2