The problem lies in the fact that your new instance of Person is overwriting the constructor.
By defining a function outside of a scope, you are essentially attaching it to the window object (the "global" scope). This means that your function Person
becomes window.Person
.
Within your click event, you are re-assigning window.Person
with
window.Person = new Person(clicked);
To resolve this issue, you could simply rename your window.Person
variable created in the click
callback. A better solution would be to utilize closures. This will help maintain a cleaner window scope and address the problem effectively.
When naming variables and constructors, it's commonly recommended to follow these guidelines:
- Constructor function names should start with an uppercase letter (e.g.,
function Person
)
- Normal variables should start with a lowercase letter (e.g.,
var person
)
This practice helps prevent confusion when using syntax like var person = new Person()
.
The revised code would look like this:
function Person(name){
this.name = name;
this.alert = function(){
alert("hello " + this.name);
};
}
function Area (location, name){
this.name = name;
this.location = location;
this.alert = function(){
alert("hello " + this.name + " you live in " + this.location);
};
}
$(document).ready(function(){
var person;
$(".button").click(function(){
var clicked = $(this).text();
person = new Person(clicked);
person.alert();
});
$(".button2").click(function(){
var location = $(this).text();
var name = person.name;
var area = new Area(location, name);
area.alert();
});
});
If you need to access the area
variable outside of the click
function, you can also consider moving var area
directly under the declaration of var person
.