I'm trying to learn to apply object-oriented principles to my Javascript programming, however I'm confused about how object "fields" or "methods" work in Javascript. I understand that properties can be dynamically assigned to Javascript objects (functions), but I don't seem to understand how to apply this in practice.
Consider the following example code snippet:
<head>
<script type="text/javascript">
var foo = function()
{
this.bar = "abc";
alert(this.bar);
}
foo.start = function()
{
alert(foo.bar);
}
</script>
</head>
<body>
<div align='center'>
<input type="submit" onclick = "foo(); foo.start();">
When the submit button is clicked, it displays the message abc, followed by undefined.
This output is contrary to my understanding and intent here. My understanding is that the line this.bar = "abc" creates a new bar property (or field) of the foo object, and assigns it the value "abc". However, when I call another method of foo, the bar property seems to have disappeared.
So, why is foo.bar undefined when I access it in foo.start?