Javascript函数有子函数/变量

时间:2011-02-05 11:49:45

标签: javascript function object

这是工作代码:

var test = function ()
{
    console.log(test.data);
};

test.data = 'hello';

test.set = function (data)
{
    test.data = data;
};

test.set('Test');
test();

这会将Test输出到我的javascript控制台。 现在我想知道,如果有办法使用这样的东西吗?

var test = {
    this: function ()
    {
        console.log(test.data);
    },

    data: 'hello',

    set: function (data)
    {
        test.data = data;
    }
};

3 个答案:

答案 0 :(得分:6)

正如我在评论中写的那样,你不能使一个对象“可以调用”。但是,您可以从第一个示例中自动执行该过程:

function extend(func, props) {
    for(var prop in props) {
        if(props.hasOwnProperty(prop)) {
            func[prop] = props[prop];
        }
    }
    return func;
}

然后用:

调用它
var test = extend(function(){
    console.log(test.data);
},
{
    data: 'hello',    
    set: function (data) {
        this.data = data;   // note that I changed it to `this.data`
    }
});

DEMO


那就是说,我认为你不应该使用这样的功能。如果您只有一个“普通”对象并使用obj.method()调用每个方法而不是obj(),则会更容易理解。

至少你必须非常仔细地记录下来。

答案 1 :(得分:3)

做这样的事情怎么样:

function Test () {
  this.data = 'hello';
  this.set = function (data)
    {
        test.data = data;
    }
  this.log = function ()
    {
        console.log(test.data);
    }
}

var test = new Test ();
test.set('Test');
test.log();

这样可以轻松创建新实例。


如果你只想要一次性,我会说你自己的建议几乎就是你想要的:

var test = {
    log: function ()
    {
        console.log(test.data);
    },

    data: 'hello',

    set: function (data)
    {
        test.data = data;
    }
};

test.set('Test');
test.log();

但也许你的问题是如何避免“.log”部分?

答案 2 :(得分:0)

您可以在对象的属性下存储任何函数。你可以调用它们:

let f = { fun1: function () 
                {
                     return 1; 
                } 
        };
f.fun1();

将完美运作。我不确定你是否可以使用'this'作为属性名称,因为它是一个关键字。可能没有问题,但可能会产生误导。