如何在每次调用对象时自动运行函数?
我有以下对象:
var myObject = {
main: function(e) {
//main
},
x: 1,
y: 2,
another: function(e) {
//another
}
}
是否可以实现以下功能?
调用
myObject();
会调用main
方法。
但是打电话给
myObject().another();
会调用another
方法。
仅使用 myObecjt()而非 myObecjt.main()
答案 0 :(得分:2)
如果我正确理解了这个问题,那么您正在寻找的代码结构如下:
var myObject = (function () {
var t = {};
t.main = function() {
console.log("main");
};
t.another = function () {
console.log("another");
};
t.main();
return t;
});
这将产生以下功能:
致电myObject();
会调用main
方法
致电myObject().another();
会同时调用main
和another
方法。
答案 1 :(得分:2)
如果你正在寻找类似链接的jquery尝试这样的事情
function myObject(){
if(this == window){
return new myObject();
}
//whatever the main method does
return this;
}
myObject.prototype.x = 1;
myObject.prototype.y = 2;
myObject.prototype.another = function(){
//whatever the another method does
return this;
}
这样的事情,会建议研究方法链和原型继承,以便清楚地解释这个问题。
或更简单的事情
function myObject(){
//whatever the main method does
return myObject;
}
myObject.x = 1;
myObject.y = 2;
myObject.another = function(){
//whatever the another method does
return myObject;//method chaining may continue
}