使用嵌套函数和默认函数定义函数 [英] Define a function with nested functions and default function

查看:63
本文介绍了使用嵌套函数和默认函数定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

function test() {
    this.foo = function() {
        console.log('foo');
        return;
    }

    this.bar = function() {
        console.log('bar');
        return;
    }
}

var action = new test();
action.foo();    //prints 'foo'

上面的代码工作正常,以防我需要调用一个动作 foo bar 内部操作 test 。但是动作 test 本身应该是一个可调用的函数。我认为如果JavaScript允许我创建这样的东西(见下文)会很酷,但正如预期的那样:

Code above works fine in case I need to call an action foo or bar inside action test. However action test itself supposed to be a callable function. I thought it would be cool if JavaScript would let me create something like this (see below) but, as expected, says:


TypeError:动作不是函数

TypeError: action is not a function



function test() {
    this.foo = function() {
        console.log('foo');
        return;
    }

    this.bar = function() {
        console.log('bar');
        return;
    }

    return function() {
        console.log('default');
        return;
    }();
}

var action= new test();
action();        //prints 'default'
action.bar();    //printf 'bar'

是否有可能实现类似的目标?

Is it possible to achieve something similar?

推荐答案

这是可能的。只需在里面创建一个函数并直接向函数对象添加其他属性:

It is possible. Just create a function inside and add other properties directly to the function object:

function test() {
  
    var result = function () {
        console.log('default');
    };
  
    result.foo = function() {
        console.log('foo');
        return;
    }

    result.bar = function() {
        console.log('bar');
        return;
    }

    return result;
}

var test = new test();
test();        //prints 'default'
test.bar();    //printf 'bar'

这篇关于使用嵌套函数和默认函数定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆