0

因此,如果我像这样在 Javascript 中声明一个对象:

var myhouse = {
    room: {
        bed: function() { return "sleep"; }
    }
}

我可以打电话:

myhouse.room.bed();

我可以制作一个可以调用的方法吗:

myhouse.room();

? 我不能只说:

var myhouse = {
    room: {
        function() { return "stuff"; },
        bed: function() { return "sleep"; }
    }
}

这是无效的。那么我错过了什么?这样做是个好主意吗?

4

2 回答 2

2

你不能用一个文字来做,你需要一个额外的赋值来设置一个函数的属性:

var myhouse = {
    room: function() { return "stuff"; }
};
myhouse.room.bed = function() { return "sleep"; };

要使其成为单个表达式,您可以使用 IEFE

var myhouse = {
    room: (function(){
        var room = room = function() { return "stuff"; }
        room.bed = function() { return "sleep"; };
        return room;
    })()
};

或逗号运算符(非常不可读,但有效):

var myhouse = {
    // using myhouse as an already declared variable
    room: (myhouse = function() {return "stuff";},
           myhouse.bed = function() {return "sleep";},
           myhouse)
};
于 2012-08-23T08:28:57.107 回答
2

如果您知道该函数也是对象,则可以使用此类语法。

var room = function() { return "stuff"; }
room.bed = function() { return "sleep"; };

var myhouse = { room: room };
myhouse.room(); // stuff
myhouse.room.bed(); // sleep

或者

var myhouse = { room: function() { return "stuff"; } };
myhouse.room.bed = function() { return "sleep"; };
myhouse.room(); // stuff
myhouse.room.bed(); // sleep
于 2012-08-23T08:27:14.050 回答