Opened 8 years ago

Closed 8 years ago

#13962 closed defect (invalid)

OOPS with attributes not working properly

Reported by: saravanadel Owned by:
Priority: blocker Milestone: tbd
Component: Core Version: 1.6.1
Keywords: Cc:
Blocked By: Blocking:

Description

I wanted to use Dojo OOPs for creating folder/file data structure using classes.

I have created the Folder class

dojo.declare("Folder", null, {
    sub_folders:new Array(),
    addSubFolder: function(folder) {
	this.sub_folders.push(folder);
    }
});

Now a simple test case

var folder = new Folder();
var sub_folder = new Folder();
folder.addSubFolder(sub_folder);
folder.addSubFolder(sub_folder);

var test_folder= new Folder();
test_folder.addSubFolder(f1);

console.log(folder); Should print Object { sub_folders=[2], more...}

But it prints Object {sub_folders=[3], more...}

The attributes are not encapsulated properly. Even though the test_folder object is modified it gets reflected it in the folder object.

I tested this using JavaScript? class declaration and this works properly.

Javascript case:

function Folder () {
    this.sub = new Array();
    this.addSubFolder = function(subfolder) {
        this.sub.push(subfolder);
    };
}

Running the above code with above test case provides the correct results.

Change History (1)

comment:1 Changed 8 years ago by bill

Resolution: invalid
Status: newclosed

This is a common beginner mistake. Your sub_folders array is shared between instances. You need to declare it in the constructor.

dojo.declare("Folder", null, {
    constructor: function(){
           this._sub_folders = [];
    },
    addSubFolder: function(folder) {
	this.sub_folders.push(folder);
    }
});

In the future, questions like this are more appropriate for the dojo-interest mailing list. (Although for this particular question you could find the answer by googling.)

Note: See TracTickets for help on using tickets.