Reputation: 21556
I was lead to this question because for some reason I was having a problem setting a value on an object variable to false.
I had
var myObject{ checkValid = false, self.getCheckValid = function(){ return checkValid; } self.setCheckValid = function(mode){ checkValid = mode; } } objectVariable = new myObject;
when I ran objectVarible.setCheckValid(true)
, I would get the true value. But when I ran objectVariable.setCheckValid(false)
the whole app would error out (except I'm developing in mobile and couldn't see the actual error returned).
But then I was wondering, if I can't set the mode to false, can I just re-initiate the entire object by calling objectVariable = new myObject;
again. This will overwrite the old object with the new object and get me back to the initialized state, which is really what I'm looking for.
Is there a reason not to do this? Or is one method better than the other? Any reason why I couldn't just set the checkValid to false?
Upvotes: 0
Views: 114
Reputation: 94499
The syntax for creating an object uses :
instead of =
to create a property. There is also no need to use .self
to access the properties. Also when assigning the object to a variable you should use the syntax var myObject = {/**properties**/};
var myObject = {
checkValid:false,
getCheckValid: function(){
return this.checkValid;
},
setCheckValid: function(mode){
this.checkValid = mode;
}
};
Working Example: http://jsfiddle.net/PSYSM/
The accessors you have placed on the object are unnecessary, you have direct access to the checkValid
property without the accessors.
var myObject = {
checkValid:false
};
alert(myObject.checkValid);
myObject.checkValid = true;
alert(myObject.checkValid);
Working Example: http://jsfiddle.net/JtfaJ/
Regarding using new with MyObject
, this is not possible since you have declared an object literal. Only one instance of this object will exist, therefore you cannot create instances of the object. If you want to create instances you will need to create a object constructor. This can be done as follows:
function MyObject(){
this.checkValid = false;
}
var myObject1 = new MyObject();
myObject1.checkValid = true;
alert(myObject1.checkValid);
var myObject2 = new MyObject();
alert(myObject2.checkValid);
Working Example: http://jsfiddle.net/PzhUV/
Upvotes: 4