Search code examples
javascriptprototypeprototypal-inheritance

JS: prototypal inheritance child method gives me the function body


So i have this constructor function and some prototype methods:

var test = function(name, surname){

    this.name = name
    this.surname = surname

}

test.prototype.hello = function(){

    console.log("hello " + this.name)

}

test.prototype.hi = function(name){

    console.log("hi " + this.name)

}

test.prototype.hi.surname = function(){

    console.log("hi " + this.surname + this.name)

}

And i call it like this:

var hii = function(){

    var x = new test("kevin", "vanhove")

    x.hello()
    x.hi.surname()

}()

Why is it that the call to x.hi.surname() is giving me this output (function body)?

hello kevin

hi function (){

    console.log("hi " + this.surname + this.name)

}


Solution

  • When you call

    x.hi.surname();
    

    the value of this inside the "surname" function will be a reference to the function "hi". It's the last . that counts. This, this.surname refers to the "surname" property of the "hi" function, which is of course the "surname" function itself.

    I can't think of a good way to set up a structure like the one you seem to want. There's only one "hi" function, on your prototype. I suppose you could create a distinct "hi" property for each constructed object, and a bound "surname" function too:

    var test = function(name, surname){
        function hi(name) {
          console.log("hi " + this.name)
        }
        function surname(){
          console.log("hi " + this.surname + this.name)
        }
    
        this.name = name;
        this.surname = surname;
        this.hi = hi;
        this.hi.surname = surname.bind(this);
    }