473,671 Members | 2,258 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Re: Replacing a private function an keeping access to private variables

Gregor Kofler wrote:
Expand|Select|Wrap|Line Numbers
  1. function foo() {
  2.    var privateVar = 42;
  3.    var privateFunc = function() {
  4.      alert(privateVar);
  5.    };
  6.    return {
  7.      replacePF: function(f) { privateFunc = f; },
  8.      accessPF: function() { privateFunc(); }
  9.    };
  10. }
  11. var obj = foo();
I am curious, why did you choose to use a factory instead of a constructor?
Expand|Select|Wrap|Line Numbers
  1. obj.accessPF(); // 42
  2. obj.replacePF(function() {
  3.    window.alert("The answer is "+privateVar);
  4. });
  5. obj.accessPF(); // privateVar is undefined
It's a closure and `privateVar' in privateFunc() is bound to the execution
context of foo(), in which `privateFunc' was declared a variable. However,
the function expression in the obj.replacePF() call creates a closure in
which `privateVar' is bound to the execution context in which the call is
executed and the anonymous Function object is created, and in which scope
chain no object has such a property.

ISTM the only way to do this is to have a public method that returns
`privateVar', which would become "protected" through this: Either

Expand|Select|Wrap|Line Numbers
  1. function foo()
  2. {
  3. var privateVar = 42;
  4.  
  5. var privateFunc = function() {
  6. window.alert(privateVar);
  7. };
  8.  
  9. return {
  10. getPrivateVar: function() { return privateVar; },
  11. replacePF: function(f) { privateFunc = f; },
  12. accessPF: function() { privateFunc(); }
  13. };
  14. }
  15.  
  16. var obj = foo();
  17.  
or

Expand|Select|Wrap|Line Numbers
  1. function Foo()
  2. {
  3. var privateVar = 42;
  4.  
  5. var privateFunc = function() {
  6. window.alert(privateVar);
  7. };
  8.  
  9. this.getPrivateVar = function() { return privateVar; };
  10. this.replacePF = function(f) { privateFunc = f; };
  11. this.accessPF = function() { privateFunc(); };
  12. }
  13.  
  14. var obj = new Foo();
  15.  
  16. and then
  17.  
  18. // 42
  19. obj.accessPF();
  20.  
  21. obj.replacePF(function() {
  22. window.alert("The answer is " + obj.getPrivateVar());
  23. });
  24.  
  25. // "The answer is 42"
  26. obj.accessPF();
(It's the usual simple getter and setter implementation as it is.)


HTH

PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm>
Jun 27 '08 #1
1 1037
Thomas 'PointedEars' Lahn meinte:
I am curious, why did you choose to use a factory instead of a constructor?
I've started switching from constructor instantiation to a factory like
pattern after reading Crockfords new book, and realizing that I tend to
have objects with a meager amount of public properties, but lots of
private functions. On the other hand I do need a factory occassionally.
Since I try to avoid mixing the patterns, I stick to factories most of
the time now.
It's a closure and `privateVar' in privateFunc() is bound to the execution
context of foo(), in which `privateFunc' was declared a variable. However,
the function expression in the obj.replacePF() call creates a closure in
which `privateVar' is bound to the execution context in which the call is
executed and the anonymous Function object is created, and in which scope
chain no object has such a property.
Yep, I know the reason, why I can't access it this way, but I was rather
tired yesterday evening and had this feeling that missed something.
ISTM the only way to do this is to have a public method that returns
`privateVar', which would become "protected" through this
[snip]

Ok, that's the approach I already use.
HTH
Sort of.

Gregor


--
http://photo.gregorkofler.at ::: Landschafts- und Reisefotografie
http://web.gregorkofler.com ::: meine JS-Spielwiese
http://www.image2d.com ::: Bildagentur für den alpinen Raum
Jun 27 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
21383
by: Rajesh Garg | last post by:
Can we have private constructors and destructors? IF yes what is the use of such constructors or destructors.....in the sense where can these be implemented in a system................. I have an idea that we can have private constructors and destructors but am not able to find a situation where they can be used... Regards RVG rajeshgarg@opussoft.com
12
2653
by: Will | last post by:
Is it possible to have private instance members in a javascript class? function myObject() { var private = 1; this.getPrivate = function() { return private; } this.incrementPrivate = function() {
4
3616
by: anonymous | last post by:
Thanks your reply. The article I read is from www.hakin9.org/en/attachments/stackoverflow_en.pdf. And you're right. I don't know it very clearly. And that's why I want to understand it; for it's useful to help me to solve some basic problem which I may not perceive before. I appreciate your help, sincerely.
8
4610
by: Chris A via AccessMonster.com | last post by:
I have an interesting problem that I have yet to come accross that I can't change data structure on because it is an export from filemaker I am reformatting for another dept. anyway. I have a table like so... Table 1 Field1 Field2 Field3 E1 April 2006 AA, BB, CC E2 April 2006 AA, BB, CC,DD, EE E3 April 2006 AA, BB
2
3982
by: Rob Long | last post by:
Hi there Is there any way to access private variables directly from within a priviliged function? I have a situation where the priviliged function's execution context contains variables of the same name as the parent context, but I want direct access to the parent context's variable. E.g. I would like to be able to do this... function Point()
9
8646
by: CDMAPoster | last post by:
About a year ago there was a thread about the use of global variables in A97: http://groups.google.com/group/comp.databases.ms-access/browse_frm/thread/fedc837a5aeb6157 Best Practices by Kang Su Gatlin, casual mention was made about using static variables as an alternative to using global variables. This caused me to think of the following: '-----Begin module code
3
1889
by: rick | last post by:
I have a situation where I want to write an extensible class that is capable of saving / restoring properties of classes derived from it. A simplified example is explained as follows;- class A { private $Save ; public function Push() {
13
1718
by: PragueExpat | last post by:
I (think) that I've come up with a pattern that I haven't seen in any publications so far and I would like some feedback. Basically, I was looking for a way to inherit private functions and I came up with this: //base private object constructor function priv(){ this.a = 1; this.b = 2;
1
1391
by: agendum97 | last post by:
On Jun 26, 4:53*pm, Gregor Kofler <use...@gregorkofler.atwrote: If possible for your scenario, you could potentially use eval for this. For example: function MyClass(val) { var printIt = function () { window.alert("1:" + val); } this.callPrintIt = function () { printIt(); }
0
8909
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8819
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8596
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8667
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6222
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4399
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2806
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2048
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1801
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.