JavaScript OOP

Pages: 12
Classes and objects in JavaScript seem super weird... Started learning JavaScript a couple days ago, just hit objects. Does javascript have classes or does it not? I have no idea, and the notation is super bizarre coming from a C++, Java, and Python background.

Anyone else agree?
What are you using to learn JavaScript? It felt natural to me, but I was using CodeCademy.com to learn JS.
Codeacademy as well heh. Was all gravy until it hit objects, then it lost me. Was just like "Alright and here's objects and it's weird notation... Moving on!"

Currently reading other sources to figure out what the hell an object really is in Javascript

And what the hell, can you just add new fields to an object on the fly?
Last edited on
I would have thought JavaScript accomplished classes in a similar way to Python?
Python classes are pretty similar to C++ and Java classes.
Last edited on
Agreed. There are multiple ways to make classes. The way I have been making objects in javascript is like this.

1
2
3
4
5
6
7
8
9
10
    function Block(posX, posY, posZ, szX, szY, szZ, texturePath) {

        this.geometry = new THREE.CubeGeometry(szX, szY, szZ);
        this.material = new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture(texturePath)});  
        this.mesh = new THREE.Mesh(this.geometry, this.material); 
        this.mesh.position.x = posX;
        this.mesh.position.y = posY;
        this.mesh.position.z = posZ;

    }    


Block() is now like a constructor, and it's member variables are the variables after this.

Then I create an instance like this,

var aBlock = new Block( 0, 102, 0, 312, 4, 100, path);

And then I can access it's members like this,

aBlock.mesh.position.x = 5;

And I can make a member function like this,
1
2
3
4
5
6
    Block.prototype.set_position = function(x, y, z) {

        this.mesh.position.x = x;
        this.mesh.position.y = y;
        this.mesh.position.z = z;
    }    


And call it like this,

aBlock.set_position(3, 4, 6);

I just chose one way and stuck with it. I'm not yet too interested in delving deeply into how javascript works, I just figure out how to do what I want with it and then do it.
Last edited on
Oh, it's kinda like Lua's tables (or vice versa). I just treat objects as maps + syntactic sugar.
closed account (3qX21hU5)
Javascript classes are quite weird in my opinion and there are different ways (Patterns) to accomplish them.

For example something like this will give you instantiation, encapsulation and inheritance but the variable will be static.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var Foo = (function() {
    // "private" variables 
    var _bar;

    // constructor
    function Foo(){};

    // add the methods to the prototype so that all of the 
    // Foo instances can access the private static
    Foo.prototype.getBar = function() {
        return _bar;
    };
    Foo.prototype.setBar = function(bar) {
        _bar = bar;
    };

    return Foo;
})();



If you don't want the variable to be static you could do something like this instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var Foo = (function() {
    // constructor
    function Foo(){
        this._bar = "some value";
    };

    // add the methods to the prototype so that all of the 
    // Foo instances can access the private static
    Foo.prototype.getStaticBar = function() {
        return this._bar;
    };
    Foo.prototype.setStaticBar = function(bar) {
        this._bar = bar;
    };

    return Foo;
})();


We lose encapsulation in this example but it is common to see private variables prefixed with a underscore and most programmers will know not to alter it since it is meant for internal use.

I borrowed the code from this post http://stackoverflow.com/questions/12610394/javascript-classes since didn't feel like typing up my own. So that thread might contain more information on the different patterns availible to making classes in JS.

Yeah, JS OOP takes a little getting used to. At least CodeCademy holds you hand just enough to get the hang of it. Like the Cash Regsiter example for the Intro to OOP II section (though, I'll admit, somethings I blanked at times and had to look back):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
function StaffMember(name,discountPercent){
    this.name = name;
    this.discountPercent = discountPercent;
}

var sally = new StaffMember("Sally",5);
var bob = new StaffMember("Bob",10);

// Create yourself again as 'me' with a staff discount of 20%
var me = new StaffMember("BHXSpecter", 20);

var cashRegister = {
    total:0,
    lastTransactionAmount: 0,
    add: function(itemCost){
        this.total += (itemCost || 0);
        this.lastTransactionAmount = itemCost;
    },
    scan: function(item,quantity){
        switch (item){
        case "eggs": this.add(0.98 * quantity); break;
        case "milk": this.add(1.23 * quantity); break;
        case "magazine": this.add(4.99 * quantity); break;
        case "chocolate": this.add(0.45 * quantity); break;
        }
        return true;
    },
    voidLastTransaction : function(){
        this.total -= this.lastTransactionAmount;
        this.lastTransactionAmount = 0;
    },
    // Create a new method applyStaffDiscount here
    applyStaffDiscount: function(employee){
        this.total -= (this.total * (employee.discountPercent / 100));
    }
    
};

cashRegister.scan('eggs',1);
cashRegister.scan('milk',1);
cashRegister.scan('magazine',3);
// Apply your staff discount by passing the 'me' object 
// to applyStaffDiscount
cashRegister.applyStaffDiscount(me);

// Show the total bill
console.log('Your bill is '+cashRegister.total.toFixed(2));

[EDIT] I realize I said it felt natural to me, but I got to thinking back and it only felt natural after I finished CA and dabbled with a few things in JS. jQuery was a fun API to learn if you are interested in Web Dev.
Last edited on by closed account z6A9GNh0
closed account (Dy7SLyTq)
holy crap now i understand why js scares a lot of people. that is some of the weirdest oop i have ever seen. ill stick to php. the weirdest oop i can get used to is python, because it doesnt have a type system (or at least not one for variables) and it has an init() constructor
I'm with you DTS, I can't live without strongly typed languages. I'm scared of just Python!
closed account (Dy7SLyTq)
i like python just because it reminds me a lot of c. if you can see it like that, its actually easy, but its not good for huge projects is the only thing. i mainly use it just for quick hacks or temp solutions to problems such as a nightly download manager.
I guess that's why I can't get into Python - I have an extremely strong aversion to C and anything like C. Thankfully C++ is so incredibly different from C that I don't even consider them related in my mind.
Last edited on
closed account (Dy7SLyTq)
c++ is my favorite and my main too, but i like to use c (and brainfuck for that reason i guess) is to keep my mind sharp. i programmed in only c++ for a long time, and took a lot for granted, like prototyping, multiple inheritance, and containers so it just keeps things in perspective. (you dont realize how amazing basic_string<char> is until you have only had access to char **'s
Python is less like C than C++ is.
I don't understand the fear of dynamic codeing. For me js was easy to learn. A variable is a variable and a function is a function. You never had to worry about types.
Have you ever had to stick your hand somewhere you couldn't see to grab an item you had never seen before? It's an instinctual fear.
Last edited on
Perhaps you mean fear of something new?

But I was once new to C++. It was very hard at first to grasp the concept of types, when I was spoiled with dynamic code. If I wasn't so set on learning game dev. I would have walked away from C++. Now C++ is my baby! I raise a glass to trying new things.

It takes all my strenght to stop myself from leaping into opengl just yet. I need to do a little more with 2D first, then 3D here I come!!
Manga wrote:
Perhaps you mean fear of something new?
Try walking while your eyes are closed. Is that fear of something new?
closed account (N36fSL3A)
I hate that part of languages that don't have data types. So too many times in python and ruby have I passed a wrong variable type in a function.
Pages: 12