<html>
<head>
<script type="text/javascript">
function Person (name, age) {
this.name = name;
this.age = age;
this.sayName = function () {
alert(this.name);
}
}
var person1 = new Person ("tom", 29);
var person2 = new Person ("frank", 21);
alert(person1.sayName==person2.sayName);
</script>
</head>
<body>
</body>
</html>
<html> <head> <script type=text/javascript> function Person (name, age) { this.name = name; this.age =
Share
There is nothing wrong with it (other than the slightly pedantic missing semicolon on line 6.)
Because the
sayNamefunction is created inside the constructor, a new function is created every time a new object is created. (So the functions are different, and==returns false)People get around this by attaching the function to the prototype object instead:
This will create only one function (saving you memory) and the alert will say ‘true’.