javascript - Some questions about OOP -
i have object called clock.
i have method of said object called time.
if used this.propertyname inside time method, give property clock object, right? if there if/else statement (within time method itself), example, needs run before value of property can assigned?
if(t.gethours() >= 12){ this.ap = "am"; }else{ this.ap = "pm"; } so, if used simple value this.ap = "hi", works fine. gives property object. if have statement shown above, property undefined. best way around this?
also, quick question since i'm starting use own objects. if have object 3 separate methods, , want use value in methods that's been declared within 1 method, assigning property of object allows me this. right?
so if used var property = "" in 1 method, way access in other methods return it. setting property object solves this? realize can experiment around i'd rather know proper way.
edit: here's example. i'm misunderstanding something. can't seem define properties within 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
the usual way avoid problems binding this 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 this being other expected be, can happen depending on how call methods (using method handler dom event example).
this example works exploiting closure, important concept in javascript should read on (google it).
Comments
Post a Comment