0

This is my first time to make an object in JS.

Can someone help me understand why the sourve did not work?

this is the full source:

<script>
function person(firstname,lastname,age,eyecolor) {
    this.firstname=firstname;
    this.lastname=lastname;
    this.age=age;
    this.eyecolor=eyecolor;

    function getName() {
        return this.firstname;
    }
}

var myFather = new person("John","Doe",50,"blue");
document.write( myFather.getName() );
</script>
Herrington Darkholme
  • 5,701
  • 1
  • 24
  • 41

2 Answers2

0
function getName() {
    return this.firstname;
}

should be

this.getName = function () {
    return this.firstname;
}

And it's better to attach such method to the prototype of person.

person.prototype.getName = function () {
    return this.firstname;
}
xdazz
  • 154,648
  • 35
  • 237
  • 264
0

here is the code.

<script>
function person(firstname,lastname,age,eyecolor) {
    this.getName =  function getName() {
        return firstname;
    }
}

document.write( (new person("John","Doe",50,"blue")).getName() );
</script>
Muhammad Irfan
  • 238
  • 1
  • 8