So I am trying to convert my web app over to being OOP-based since that’s how I learned to program in the first place. I have all my functions and everything defined, but I’m running into a problem.
Let’s say in the index.php I open a script tag and create an object function:
<script type="text/javascript">
function myObject(_string){
this.string = _string;
this.get_string = function(){
return this.string;
}
}
</script>
No biggie.
Now if I call it, it works fine if I do this:
var my_object = new myObject("this is a string");
console.log(my_object.get_string) // logs "this is a string"
but if I wrap it in a domReady, the object never gets created, and calling my_object returns a reference error:
$(document).ready(function() {
var my_object = new myObject("this is a string");
console.log(my_object); // returns reference error
});
I get this same problem if I embed a function inside my object and try to call it:
<script type="text/javascript">
function myObject(_string){
this.string = _string;
this.get_string = function(){
return this.string;
}
this.set_string = function(new_string){
this.string = new_string;
}
}
my_object = new myObject("this is a string");
my_object.set_string("this is a new string"); // returns reference error
my_object.set_string() // Returns reference error
my_object.set_string // returns a string containing the function
</script>
Seriously confused over this. Can anyone help?
This should work regardless of where your code is placed
And call the like: