I am new to JavaScript and may not be using correct terms so please bear with me.
I am expect the following be displayed on the page Hello my name is John Smith and I am 29 years old. Hello my name is Suzie Alport and I am 24 years old.
I want to understand why can't Suzie refer to John's greet method?
<script>
var employees = {
john: {
name: "John Smith",
age: 29,
job: "web developer",
greet: function(){
document.write("Hello my name is " + this.name + " and I am " + this.age + " years old. ");
}
},
suzie: {
name: "Suzie Alport",
age: 24,
job: "nursery assistant",
greet: employees.john.greet
}
};
employees.john.greet();
employees.suzie.greet();
</script>
Thanks
As of the time that you're creating the object you're assigning to the suzie
property, employees
is undefined
. The property initializers are evaluated before the overall expression is complete.
Here's the order in which things happen above:
employees
with the initial value undefined
. employees
). john
property value). "John Smith"
and creates a property on the blank object from #3 called name
, giving it that value. age
, job
, and greet
. john
property on the object from #2 above. suzie
). "Suzie Alport"
and creates a property on the object from #7 called name
, giving it that value. age
and job
. employees.john.greet
and fails because employees
is undefined
. If you break it into two pieces, it works (until document.write
blows things up):
var employees = {
john: {
name: "John Smith",
age: 29,
job: "web developer",
greet: function(){
document.write("Hello my name is " + this.name + " and I am " + this.age + " years old. ");
}
}
};
employees.suzie = {
name: "Suzie Alport",
age: 24,
job: "nursery assistant",
greet: employees.john.greet
};
employees.john.greet();
employees.suzie.greet();
That works because before we try to evaluate employees.john.greet
, a reference to the object created in #2 above has been assigned to the employees
variable.
Side note:
Avoid using document.write
in modern web pages and applications. Instead, use DOM methods . document.write
only works the way you likely want it to during the initial page load; after initial page load, it will wipe out the existing document entirely and start writing a new document in the same window.
For instance, you can append paragraphs to the document.body
like this:
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
Live Example with both of the above ( source )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.