实现以下目标的最佳设计模式是什么(不起作用)?
var obj = (function() {
// code defining private variables and methods
var _obj = {
property: value,
method1: function() {
// do stuff
},
method2: function() {
// use property
var prop = _obj.property; // obviously doesn't work
// call method1
obj.method1(); // "obj" not finished being defined yet!
}
};
// obviously now I could do...
var prop = _obj.property;
return _obj;
})();
// and I could now do...
obj.method1();
我认为应该起作用的变体是
var obj = (function() {
var property = value,
method1 = function() {
// do stuff
},
method2 = function() {
// use property
var prop = property;
// call method1
method1();
},
_obj = {
property: property,
method1: method1,
method2: method2
};
return _obj;
})();
类似地,它对于打算用操作符创建的对象是如何工作的new
?在构造函数本身中,您可以编写this.method()
. 但是如果你想保持构造函数很小,只定义那些可能在创建时定制的东西,然后在原型中定义其余的东西呢?(这似乎是常见的模式。)原型中的属性/方法可以以任何方式交互吗?
var MyObj = function(name) {
this.name = name;
};
var obj = new MyObj('Bob');
MyObj.prototype = {
called_often: function() {
// lots more code than just the following
return document.getElementById('someID').value;
},
global_default: 'value', // can be changed, so need to pull value when run
does_stuff: function(value) {
var str = global_default + value, // can't access global_default on its own
input = MyObj.called_often(), // doesn't work; MyObj.prototype.called_often() DOES
name = this.name; // 'this' used in the prototype doesn't work
// even within a created object
return name + input + str;
}
};
我敢肯定,每当我遇到这个问题时,都会有更好的方法来实现我的结果。此代码不是特定情况,只是说明一般问题。因此,对于我遇到的那些特定情况,您将无法为我提供替代方案。但也许你可以帮助我的整体思考。