Brian Ellis
Brian Ellis

Reputation: 2441

Difference in terminology? JS Scope

I'm getting more in the OO side of JS now and less basic DOM manipulation and interaction parts. The one thing that is confusing as I'm brushing up on my books is the terminology of global, local, public, private variables.

From what I gather it seems that private/public is more borrowed from JAVA users crossing over but in fact they're simply global and local variables.

Am I wrong in assuming this?

Upvotes: 0

Views: 41

Answers (2)

user5548116
user5548116

Reputation:

Amaizing explanation in this article around this question P.S. Douglas Crockford

Public Constructor

function Container(param) {
    this.member = param;
}

Prototype

Container.prototype.stamp = function (string) {
    return this.member + string;
}

Private

function Container(param) {
    this.member = param;
    var secret = 3; //private
    var that = this; // private
}

function Container(param) {

    function dec() {  // private method
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;

    this.service = function () {
        return dec() ? that.member : null;
    };
}

I hope this article will help you.

Thanks

Upvotes: 2

Marcos Pérez Gude
Marcos Pérez Gude

Reputation: 22158

To understand the public and private variables in a Javascript object:

var NewObject = function() {
  
  this.public = "that's public";
  var private = "that's private";
  
};

var instance = new NewObject();
console.log(instance.public); // that's public
console.log(instance.private); // undefined

Upvotes: 1

Related Questions