Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Javascript have privileged functions

Tags:

javascript

After an discussion at work, I still do not have an satisfying answer about the following, in no other programming language we speak of privileged functions.

var kid = function(name)
{
    // Private
    var idol = "Paris Hilton";

    // Privileged
    this.get_idol = function()
    {
        return idol;
    };
}

The only logic I could think of is that if you make an public function return an private variable, that function is 'privileged' to do this (because you cannot call it directly).

We can do the same in php but we do not use this fancy name, nor can i recall any other language using this term.

You might even come to thing that if you need an 'privileged' function your whole approach is wrong, since if you need it accessible from the outside, why not make it public directly.

On the other hand the private variable cannot be changed from the outside and therefor it would become protected. but displayed to the outside.

In the end, as an somewhat newcomer to plain javascript, the term is somewhat confusing and imho just a fancy name to make it more confusing, because then in php it would become also like javascript :

class kid
{
    // Private
    private idol = "Paris Hilton";

    // PUBLIC OR PRIVILEGED ? 
    public function get_idol()
    {
        echo $this->idol;
    }
}

it does the same but is just a public method.

like image 741
DonSeba Avatar asked Mar 10 '11 21:03

DonSeba


2 Answers

Javascript doesn't have privileged or whatever functions. All it's functions are closures and that's what is in use there, C# got this also and most functional languages.

The ECMA norm for the language is available if you need, the word privileged don't appear once inside of it.

The term seem to come from http://www.crockford.com/javascript/private.html but it's just a simplification of the closure concept to a specific case of their usage targeted i guess to OOP-programmer types.

Javascript could be more powerful design-wise than most OOP languages but you need to approach it with an open mind and by understanding functional concepts. Trying to coerce it to become yet-another-OOP-language would be both a bad idea and a shame.

like image 188
Julien Roncaglia Avatar answered Oct 24 '22 15:10

Julien Roncaglia


I've never heard of a privileged function; the correct term is a closure: you define a function in a scope which has access to variables defined in its outer scope. Closures can be used in lots of languages (Javascript, Python, Lisp/Scheme all do, and Java does in part through inner classes that can reach final variables in the closure scope).

Member variables of an object (e.g. this.foo in Java/Javascript or this->foo in PHP) are different.

like image 45
Jason S Avatar answered Oct 24 '22 15:10

Jason S