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 clicke开发者_高级运维d, 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 this
refers to inside the function. When you create a new foo
object like this:
var f = new foo();
...then this
refers to the new object. However, when the new
operator is omitted, like this:
var f = foo();
...then the context is the global window
object. In that case, this line:
this.bar = "abc";
...sets the value of a property on window
, not the new object.
精彩评论