[英]module reveal prototype pattern - private variables
I am using the module reveal prototype pattern ( https://weblogs.asp.net/dwahlin/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-prototype-pattern ), and am having trouble accessing my this variable in my prototype functions. 我正在使用模块显示原型模式( https://weblogs.asp.net/dwahlin/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-prototype-pattern ),并且无法访问我的这个变量在我的原型函数中。 I have this code:
我有以下代码:
myapp.ConfirmationWindow = function (temptype) {
this._type = temptype;
};
myapp.ConfirmationWindow.prototype = function () {
this._showConfirmationWindow = function (message) {
var a = this._type; //valid
return _showWindow("hello");
}
this._showWindow = function (message) {
var a= this._type; //invalid
}
return {
showConfirmationWindow: _showConfirmationWindow
};
}();
I am able to access this._type in _showConfirmationWindow(), but am not able to access this._type in _showWindow. 我可以在_showConfirmationWindow()中访问this._type,但不能在_showWindow中访问this._type。 The different is that the prototype is setting _showConfirmationWindow() as public and _showWindow as private, but why doesn't _showWindow get access to this._type.
不同之处在于原型将_showConfirmationWindow()设置为public,将_showWindow设置为private,但是_showWindow为什么无法访问this._type。 Why is this the case.
为什么会这样呢?
One solution I found is to pass this as an extra parameter in _showWindow 我发现的一种解决方案是将其作为_showWindow中的额外参数传递
_showWindow
don't have a this
reference to your instance because it's not part of ConfirmationWindow prototype
because by returning only showConfirmationWindow
, it never gets assigned to the prototype. _showWindow
没有对您的实例的this
引用,因为它不是ConfirmationWindow prototype
的一部分,因为仅返回showConfirmationWindow
,就永远不会将其分配给原型。 You could use call
to invoke your private functions like: 您可以使用
call
来调用您的私有函数,例如:
_showWindow.call(this, "hello")
Or adding a second argument to _showWindow
like and pass the this
reference when you invoke it: 或向
_showWindow
添加第二个参数,并在调用它时传递this
引用:
_showWindow(message, self)
But i would prefer the first one. 但是我更喜欢第一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.