Search code examples
javascriptprototype

Why function that is property of the object isn't accessible once we add the same function to its prototype?


I have some basic understanding of why we use prototypical inheritance, while doing some stuff in my app I realized you can't really access a function once you add the function of the same name to its prototype. Why is that, Here is my code:

function person(firstname, lastname) {
    this.firstname = firstname,
    this.lastname = lastname,
    this.greet = function() {
        console.log('hey there', this.lastname + '  ' + this.firstname);
    }
}

var jane = new person('jane', 'Doe');
jane.greet();
var john = new person('john', 'smith');
john.greet();

function person(firstname, lastname) {
    this.firstname = firstname,
    this.lastname = lastname
}

person.prototype.greet = function() {
    console.log('hey there', this.lastname + '  ' + this.firstname);
}

var jane = new person('jane', 'Doe');
jane.greet();
var john = new person('john', 'smith');
john.greet();

Error thrown is:

"test.js:10
jane.greet();
     ^
TypeError: jane.greet is not a function"

Solution

  • Works for me. The only issue I could think of is you have re-declared (or tried to re-declare) the same method person within the same code block.

    Edit for clarification: As pointed out by ASDFGerte, the second declaration of person overwrites the first version, which removes the internal method greet. You then try to use greet before the prototype expands person and re-adds the greet function.

    function person(firstname, lastname) {
        this.firstname = firstname,
        this.lastname = lastname,
        this.greet = function() {
            console.log('hey there', this.lastname + '  ' + this.firstname);
        }
    }
    var jane = new person('jane', 'Doe');
    jane.greet();
    var john = new person('john', 'smith');
    john.greet();
    
    function person2(firstname, lastname) {
        this.firstname = firstname,
        this.lastname = lastname
    }
    person2.prototype.greet = function() {
        console.log('(2) hey there', this.lastname + '  ' + this.firstname);
    }
    var jane2 = new person2('jane2', 'Doe');
    jane2.greet();
    var john2 = new person2('john2', 'smith');
    john2.greet();