我有这个对象
fieldsCreator的成员为每个字段保存创建者方法
我的问题是如何在fieldsCreators
中调用创建者方法,如下所述:
var obj={
creator:function(ch) {
....
....
....
},
fieldsCreators:{
INVITER: function () {
return creator('a'); //HOW DO I CALL creator METHOD?
},
CUSTOMER: function () {
return creator('b'); //HOW DO I CALL creator METHOD?
}
}
}
答案 0 :(得分:2)
obj.creator(...)
不起作用吗?
您正在定义一个名为'obj'的实例,因此您应该可以使用该名称。
EDIT-- 这可能就是你想要的 -
var obj={
creator:function(ch) {
....
....
....
},
self : this,
fieldsCreators:{
INVITER: function () {
return self.creator('a'); //HOW DO I CALL creator METHOD?
},
CUSTOMER: function () {
return self.creator('b'); //HOW DO I CALL creator METHOD?
}
}
}
答案 1 :(得分:2)
你也可以使用这样的模式:
var obj = (function() {
var methods = {
creator: function(ch) {
},
fieldsCreators:{
INVITER: function () {
return methods.creator('a');
},
CUSTOMER: function () {
return methods.creator('b');
}
}
};
return methods;
})();
这有用吗?假设您希望为所有方法提供对变量的访问权限,但只能在obj中查看。如果obj只是一个对象,它就不能这样做,它需要一个函数的作用域。例如:
var obj = (function() {
// everything declared with var won't be visible to the rest
// of the application, which is good encapsulation practice.
// You only return what you want to be publicly exposed.
var MYPRIVATEINFO = "cheese";
var methods = {
creator: function(ch) {
// you have access to MYPRIVATEINFO here
// but the rest of the application doesn't
// even know about it.
},
fieldsCreators:{
INVITER: function () {
return methods.creator('a');
},
CUSTOMER: function () {
return methods.creator('b');
}
}
};
return methods;
})();
如果您不想为对象命名,可以像这样构建它,这就是为什么私有环境是关键:
var obj = (function() {
var creator = function(ch) {
};
return {
// if you wish, you can still expose the creator method to the public:
creator: creator,
fieldsCreators: {
INVITER: function () {
return creator('a');
},
CUSTOMER: function () {
return creator('b');
}
}
};
})();