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,979
  • 1
  • 27
  • 43

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
  • 158,678
  • 38
  • 247
  • 274
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
  • 228
  • 1
  • 8