因此,如果我在Javascript中声明一个对象,那么:
var myhouse = {
room: {
bed: function() { return "sleep"; }
}
}
我可以致电:
myhouse.room.bed();
我可以使用以下方法创建一个可调用的方法:
myhouse.room();
?我不能只说:
var myhouse = {
room: {
function() { return "stuff"; },
bed: function() { return "sleep"; }
}
}
它无效。那我错过了什么?这样做甚至是个好主意吗?
答案 0 :(得分: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
答案 1 :(得分: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)
};