您可以通过多种方式做到这一点;以下使用闭包。
var myObj = (function() {
var a;
return{
callMefirst: function() {
var thisObj = this;
a = 'chocolate cookie';
thisObj.callMe();
},
callMe: function() {
alert(a);
}
}
})()
myObj.callMefirst();
使用闭包和对象初始化:
var myObjF = function(pass) {
var a=pass;
return{
callMefirst: function() {
var thisObj = this;
thisObj.callMe();
},
callMe: function() {
alert(a);
}
}
}
var myObj=myObjF("hello");
myObj.callMefirst();
使用函数作为对象:
var myObjF = function(pass) {
this.a=pass;
this.callMefirst = function() {
var thisObj = this;
thisObj.callMe();
};
}
myObjF.prototype.callMe = function() {
alert(a);
}
var myObj=new myObjF("hello");
myObj.callMefirst();