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?
JavaScript functions execute in a context that determines what
thisrefers to inside the function. When you create a newfooobject like this:…then
thisrefers to the new object. However, when thenewoperator is omitted, like this:…then the context is the global
windowobject. In that case, this line:…sets the value of a property on
window, not the new object.