Take the 2-minute tour ×

I am from c# object oriented background and which to work similar priniciples in javascript. Any good I articles that could help with me research?

This is an example i put together for a Product Javascript object:

function Product() {
    this.reset = function () {
        this.id = 0;
        this.name = '';

Product.prototype = {
    loadFromJson: function (json) {
        this.id = json.Id;
        this.name = json.Name;

checkAvailability: function (qty) {
    // Just to illustrate
    return true;

So to create an instance of Product:

var p = new Product();

To access a public method:

var isAvailable = p.checkAvailability(1);

To access a public property:

var name = p.name;

Is the reset function I create a valid private function?

Is what I am doing above correct or is there a better way? I am new to this!

Also, if I create an instance of product in another javascript file, can I get intellisence on the properties of the Product object?

share|improve this question

3 Answers 3

up vote 1 down vote accepted

The reset is this.reset(); so that is in the scope of the object and thus could be called public, but remains in that scope. In your example p.reset(); but reset(); fails.

Better way? It depends, some circumstances require this complex, some do not. There are a number of ways to instantiate objects (everything is an object in JavaScript) and your examples are some of the ways.

No intellisence unless you build and attach your own (a LOT of work). (search on jQuery intellisence to see how that is done)

See this for some more regarding namespace. Note the internal and public functions and variables.

var myStuffApp = new function()
    var internalFunction = function()
        alert('soy una función interna');
    this.publicFunction = function()
        alert('soy una función pública');
    var test1 = 'testing 1';//private/internal
    this.test2 = 'testing 2';// namespaced
    testA="ho";// global
share|improve this answer

I suggest the read this msdn page for basic information. It's like a crash course for c# oriented developers.

share|improve this answer

Is the reset function I create a valid private function?

No. It differs from the functions set on prototype because you get a different copy of reset for every instance of Product:

var p1= new Product();
var p2= new Product();
alert(p1.loadFromJson===p2.loadFromJson); // true
alert(p1.reset===p2.reset); // false

but it is not private. You can still do:

var p= new Product();

Whilst you can do private functions in JavaScript using closures, it's almost never worth it. Consider just using the Python convenition of naming all members you don't intend to be used outside the implementation with a preceding underscore.

See this question for extensive discussion of JS object models.

share|improve this answer

Your Answer


