Javascript 内部函数返回父函数,如何返回?

Javascript 内部函数返回父函数,如何返回?,javascript,node.js,this,Javascript,Node.js,This,我正在经历一个JavaScript模式,链接 这里有这样的代码 function thisFunc(fullName){ var that = this; this.firstName = function(name){ fullName = fullName + name; return this; }; this.lastName = function(name){ fullName = fullName +

我正在经历一个JavaScript模式,链接

这里有这样的代码

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'));
在最后一行,我正在打印函数firstName的返回值,我得到如下输出

thisFunc{firstName:[函数],lastName:[函数],显示: [功能]}


为什么它返回firstName的父函数thisFunc,我希望它会返回firstName。当我说“returnthis”和“returnthat”时,我看到了相同的结果。

因为
firstName()
的返回是实际的父函数。如果您希望它返回
firstName
函数,那么不要调用它,只需调用它即可

console.log(y.firstName);

希望我正确理解了您的问题。

因为返回的
firstName()
是实际的父函数。如果您希望它返回
firstName
函数,那么不要调用它,只需调用它即可

console.log(y.firstName);

希望我正确理解了您的问题。

firstName函数返回'that',因此您的对象为'y'。结果是好的。你的功能是链式的,所以每次你都会返回你的对象。如果需要fullName,请添加如下函数。getFullName=function(){return fullName;};或者使用show函数在callback中获取全名。firstName函数返回'that',因此对象为'y'。结果是好的。你的功能是链式的,所以每次你都会返回你的对象。如果需要fullName,请添加如下函数。getFullName=function(){return fullName;};或者使用show函数在回调中获取全名。