0

I am going through one of the JavaScript pattern, chaining.

Here I have code like this

function thisFunc(fullName){
    var that = this;
    this.firstName = function(name){
        fullName = fullName + name;
        return this;
    };

    this.lastName = function(name){
        fullName = fullName + ' ' + name;
        return that;
    };

    this.show = function(callback){
        callback(fullName);
        return that;
    };
}

var x = new thisFunc('');
x.firstName('Karthikeyan').lastName('Sundararajan').show(function(result){
    console.log(result);
});

var y = new thisFunc('');
console.log(y.firstName('Karthik'));

At the last line, am printing the return value of function firstName, I got output like this.

thisFunc { firstName: [Function], lastName: [Function], show: [Function] }

Why it is returning thisFunc which is parent of firstName, I expected it will return firstName. And I am seeing same result when I say, 'return this' and 'return that'.

karthikeayan
  • 4,291
  • 7
  • 37
  • 75
  • firstName function return 'that', so your object 'y'. The result is good. Your function are made to chain so you return your objet each time. If you want the fullnamme add a function like this.getFullName = function(){ return fullName; }; Or use your show function to get the fullName in the callback. – PortePoisse Mar 24 '17 at 14:26

1 Answers1

2

Because the return of firstName() is the actual parent function. If you want it to return the firstName function then don't call it, just do

console.log(y.firstName);

I hope I understood your question correctly.

JorgeObregon
  • 3,020
  • 1
  • 12
  • 12