/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] OO Javascript – Private and privileged functions

Hi,

I’m trying to write some OO javascript and I’m running into a snag.

I have a private function that is trying to call a privileged function and it’s acting as though the private function can’t see the privileged one. Is this a rule that I just don’t know about?

So, for example:

[code]
var updatePage = function(xmlDocument, startPos, container){
if (xmlDocument != null){
processListings(xmlDocument, container);
}

for (var i = startPos; i < getNumResults(); i++){
addToListingsDiv(container[i]);
}

getPrevListings(false);
getNextListings(false);
}

this.getPrevListings = function(updatePage){
//Code
}
[/code]

Should I be doing this a different way?

Thanks,
Chris

to post a comment
JavaScript

24 Comments(s)

Copy linkTweet thisAlerts:
@toicontienFeb 03.2009 — I'm not seeing your privileged functions. Is that the full definition for updatePage? If not, can you please post that?
Copy linkTweet thisAlerts:
@golfinusaauthorFeb 03.2009 — Maybe I'm misunderstanding privileged vs private vs public.

The way I understand it is as follows:

Private:
<i>
</i>var myFunction = function(){

}


Privileged:
<i>
</i>this.myFunction = function(){

}


Public:
<i>
</i>this.prototype.myFunction = function(){

}


What I was considering the privileged functions were
<i>
</i>getPrevListings(false);
getNextListings(false);

Definitions:
this.getPreviousListings(updatePage){
//Code here
}

&amp;

this.getNextListings(updatePage){
//Code here
}
Copy linkTweet thisAlerts:
@golfinusaauthorFeb 03.2009 — It should also be noted:

Inside updatePage - I tried using this.getNextListings() and this.getPrevListings() as well.

Both times it told me functions were undefined and/or didn't exist.

Thanks,

C
Copy linkTweet thisAlerts:
@voidvectorFeb 03.2009 — JavaScript doesn't support private/privileged method. What you read about private/privileged methods, probably from this page, is a way to "emulate" those features using JavaScript syntax and closure. So you have to follow the syntax exactly!!!

Based on the limited code you presented, your private/privileged functions are not encapsulated in a "class" container, so it wouldn't work.
Copy linkTweet thisAlerts:
@golfinusaauthorFeb 03.2009 — I'm sorry I didn't show that they were included in a 'class', but they are. So, that isn't the reason.

Any other ideas?
Copy linkTweet thisAlerts:
@voidvectorFeb 03.2009 — <i>
</i> getPrevListings(false);

should probably be
<i>
</i> this.getPrevListings(false);
Copy linkTweet thisAlerts:
@golfinusaauthorFeb 03.2009 — Okay, I'm pretty sure I tried that and it told me the function didn't exist. But, I will try it again tonight and let you know.

Thanks a ton for the input.

-C
Copy linkTweet thisAlerts:
@toicontienFeb 03.2009 — This might be more along the lines of what you want:
[code=php]function UpdatePage(xmlDocument, startPos, container) {

// Private
var addToListings = function(c) {
// Code here
};

// Public
this.getNextListings = function(x) {
// Code here
};

// Public
this.getPrevListings = function(x) {
// Code here
};

// Begin constructor code
if (xmlDocument != null){
processListings(xmlDocument, container);
}

for (var i = startPos; i < getNumResults(); i++){
addToListingsDiv(container[i]);
}

this.getPrevListings(false);
this.getNextListings(false);
// End constructor code
}

UpdatePage.prototype = {

// Shared public methods and properties

};[/code]
Copy linkTweet thisAlerts:
@rnd_meFeb 04.2009 — Maybe I'm misunderstanding privileged vs private vs public.

The way I understand it is as follows:

Private:
<i>
</i>var myFunction = function(){

}


Privileged:
<i>
</i>this.myFunction = function(){

}


Public:
<i>
</i>this.prototype.myFunction = function(){

}

[/QUOTE]

that's not right.

prototype has nothing to do with public or private, it controls inheritance.

thinking of the word "prototype" as the word "template" makes more sense (to me at least). the properties and methods on the template, or .prototype, are available for each object ( one function, being reused on every instance).

the private code is indeed private, though it might be better to write it:

<i>
</i>function myFunction (){

}

that way, you can place the function anywhere inside the constructor, using it before the function def appears. it's a little more flexible that way...


on the interface level, there is no difference between a privileged and a public method.

the difference is what happens inside the two functions.

for instance, a standard constructor:

[CODE]function Demo(strName){
var name = strName.toUpperCase();
}[/CODE]


This yields a [U]blank object[/U] when invoked.

it is impossible to reach the name information simply by having the resulting object.


so, add a public property to the demo object:
[CODE]function Demo(strName){
var name = strName.toUpperCase();
this.name = name;
}[/CODE]


now, we can see a .name property in the object.

note that the property (and resulting information) can not only be read by having the object, it can be changed as well:

[CODE]
function Demo(strName){
var name = strName.toUpperCase();
this.name = name;
}

var person = new Demo("fred");

person.name = "bob";

alert (person.name); //shows "bob"

[/CODE]


if we want "read only" access to that information, we must hide it behind a method.

any property can be changed, so we don't want a dot connecting the data to the read request. example:

[CODE]
function Demo(strName){
var name = strName.toUpperCase();
this.getName = function(){ return name; }
}

var person = new Demo("fred")
alert(person.name);// shows "undefined"
alert(person.getName());// shows "FRED"

[/CODE]



in this pattern, getName() constitutes a privileged method.

it can access the name information that is not publicly available, and return it to anything that has access to just the object.





-----------
@voidvector:

"privileged" is not a mainstream programming term, so i would say it's up to crockford to label his pattern.

unlike other languages, javascript does not have "protected" methods/properties at all...
Copy linkTweet thisAlerts:
@Jeff_MottFeb 04.2009 — I think it's a misnomer to call any method in JavaScript a "privileged" method. Both public methods and private functions can access non-public information. If every method and function is equally privileged, then really there are no special privileges.
Copy linkTweet thisAlerts:
@rnd_meFeb 04.2009 — I think it's a misnomer to call any method in JavaScript a "privileged" method. Both public methods and private functions can access non-public information. If every method and function is equally privileged, then really there are no special privileges.[/QUOTE]

yeah, privileged seems like the category of code we call getters and setters...

I do think that there is a subtle distinction going on here though.

keep in mind though that not all public methods are necessarily able to access private information.

because protecteds reach privates using closure, protecteds must be defined inside the constructor, whereas publics can come from anywhere, anytime.

for example, if i merge two objects, the methods of one will not be able to see private members (vars) of the other, only the "this.somethings".

in that case, everything would not be equally privileged, and we do need a word.

i guess for lack of something better "privileged" is not bad.
Copy linkTweet thisAlerts:
@Jeff_MottFeb 04.2009 — Good point. You're right. I stand corrected.
Copy linkTweet thisAlerts:
@AluminXFeb 04.2009 — Not sure at what tutorial/book your reading but as far as js goes a Function Object can be private or public to it's containing object.
[code=php]function myParentFunc() //containing function object
{
var myDat; //private data
function myPrivateFunc()
{
//This function cannot call myPublic function
//This function can call myPublicFunction2
}
var myPublicFunction2 = function()
{
//This function can call myPrivateFunc
//This function cannot call myPublicFunction
}
this.myPublicFunction2 = myPublicFunction2;//create a reference

this.myPublicFunction = function()
{
//this function can call myPrivateFunc
//This function can call myPublicFunction2
}
}
var myObject = new myParentFunc();// new instance of the function object
myObject.myPublicFunction();
myObject.myPublicFunction2();[/code]

Hope this helps
Copy linkTweet thisAlerts:
@Jeff_MottFeb 04.2009 — AluminX, try this in addition to your posted code.

myParentFunc.prototype.myPublicButNonPrivilegedFunction = function() {
// This function cannot call anything that is private
alert(myDat); // Error: myDat is not defined
}

myObject.myPublicButNonPrivilegedFunction();
Copy linkTweet thisAlerts:
@rnd_meFeb 04.2009 — AluminX, try this in addition to your posted code.
[/QUOTE]

one solution?

priveledge flows down functions, and peers can share parents using closure

[CODE]
var myObject = (function(){

var myDat ="hello"; //private data

function myParentFunc() //containing function object
{

function myPrivateFunc()
{
//This function cannot call myPublic function
//This function can call myPublicFunction2
}
var myPublicFunction2 = function()
{
//This function can call myPrivateFunc
//This function cannot call myPublicFunction
}
this.myPublicFunction2 = myPublicFunction2;//create a reference

this.myPublicFunction = function()
{
//this function can call myPrivateFunc
//This function can call myPublicFunction2
}
}

myParentFunc.prototype.myPublicButNonPrivilegedFunction = function() {
// This function cannot call anything that is private
alert(myDat); // Error: myDat is not defined
}


return new myParentFunc();// new instance of the function object

}());


myObject.myPublicFunction();
myObject.myPublicFunction2();
myObject.myPublicButNonPrivilegedFunction();
[/CODE]
Copy linkTweet thisAlerts:
@Jeff_MottFeb 04.2009 — one solution?

priveledge flows down functions, and peers can share parents using closure[/quote]
Well of course. I didn't say that was code I would write. I was posting an example for AluminX. All it was meant to do was illustrate privileged and non-privileged methods.
Copy linkTweet thisAlerts:
@golfinusaauthorFeb 04.2009 — What do you mean by

one solution?

priveledge flows down functions, and peers can share parents using closure
[/quote]

Specifically - "privileged flows down functions"

Are you implying that the order of the function definition matters as to when/where you can use that function?

Also, back to the original problem. I wasn't able to call a privileged function from a private function either by including 'this.privilegedMethod()' before or by just using the function name. To work around this, I include a variable self at the top of the object and used 'self.privilegedMethod()' and it worked.

<i>
</i>function myTool () {
var updatePage = function(xmlDocument, index){
//Code here
self.getPrevListings(false);
self.getNextListings(false);
}

this.getNextListings = function(updateFlag){
//Code here
}

this.getPrevListings = function(updateFlag){
//Code here
}
}


I'm not 100% sure why this worked or if there was a better way to do it, but I found the reference from this link:

http://blog.jdbartlett.com/2006/07/javascript-private-instance-variables.html

I will study what was written more in detail today to understand more what everyone is talking about, but I think I'm starting to get the gist of things. I really appreciate everyone's activity with this post as I'm learning a ton! Thank you all soo much!

-C
Copy linkTweet thisAlerts:
@toicontienFeb 04.2009 — You need to declare the "self" variable before using it:
[CODE]function myTool () {
[B]var self = this;[/B]
var updatePage = function(xmlDocument, index){
//Code here
self.getPrevListings(false);
self.getNextListings(false);
};

this.getNextListings = function(updateFlag){
//Code here
};

this.getPrevListings = function(updateFlag){
//Code here
};
}[/CODE]

The "self" variable is set to [B]this[/B] due to a quirk in the ECMA specification, where the "this" keyword inside a function defined inside a function (updatePage) doesn't point to the containing function. Using the code above, the "this" keyword inside the updatePage function definition doesn't point to the instance of the myTool class. Declaring a variable called "self" and making it equal to [B]this[/B] gets around this quirk.
Copy linkTweet thisAlerts:
@golfinusaauthorFeb 04.2009 — Okay, that makes sense. I kind of figured it was something along those lines - that 'this' used inside of the function is different than 'this' used inside the object - at least, that's what I got from what you said.

Btw, I was declaring self before using it, I just didn't include it in the code. Sorry about that. I'm working on being more specific.

Again, thanks a ton for the help!

-C
Copy linkTweet thisAlerts:
@AluminXFeb 04.2009 — also the convention is that = this, instead of self = this.
Copy linkTweet thisAlerts:
@golfinusaauthorFeb 04.2009 — rnd_me: could you please clarify

priveledge flows down functions, and peers can share parents using closure
[/quote]


Thanks,

-C
Copy linkTweet thisAlerts:
@rnd_meFeb 04.2009 — rnd_me: could you please clarify

priveledge flows down functions, and peers can share parents using closure

Thanks,

-C[/QUOTE]

in one sentence:

functions inside other functions can reach the vars of the outer function.

more:

functions are the only way to control scope in javascript.

you can go up to an outer function's vars, but not down into an inner function's vars.

an academic example:
[CODE]

function Demo(){
var a=1;

function DemoInner(){
var b=2;

function DemoInnerMost(){
var c=3;
alert( a+b+c); //shows 6
}

DemoInnerMost();
}

DemoInner();
}

Demo();
[/CODE]


notice how DemoInnerMost can reach the outer vars a,b, and the local var c.

however:

Demo cannot see var b or c

DemoInner cannot see var c


the takeaway:

javascript is all about functions.

wrapping a function around code will enable var statements within to be reachable by everything enclosed by the function.

you can convert plain old global code (the stuff that runs raw in the script file, not as part of an event) to a function, and the operation is preserved.

all of the old global vars are now local vars, but are still reachable by all the code. Even though the vars cannot be reached outside the function, to the code they still behave as globals, due to closure.
Copy linkTweet thisAlerts:
@golfinusaauthorFeb 04.2009 — So, the functions are actings/enforcing the closure then, correct?
Copy linkTweet thisAlerts:
@toicontienFeb 04.2009 — The functions [I]are[/I] the closure. A function within a function constitutes the closure.
×

Success!

Help @golfinusa spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...