Objects in Javascript

In Javascript, there are many ways, it seems, to create, instantiate, and edit objects. As part of my ongoing (noble) quest to make clear these curious structures, I want to create a resource for myself (and friends!) for how to manipulate objects in Javascript. Then I want to go back and compare how Python handles objects & what you can and can’t do with either language. MASTERY!

Ways to Make Objects

1

var rachelsObjectLiteral {
    objectColor: "red",
    objectSize: "friggin' huge",
    rachelsMethod: function (parameterToCall) {
        console.log("this is a 'hidden' function or method of the object
        rachelsObjectLiteral, calling " + parameterToCall + ".  the way to 
        call this Method is only via the object name, so 
        'rachelsObjectLiteral.rachelsMethod(argumentToCall)");
    },
    var rachelsOtherMethodMadePlain = function () {
        console.log("and this one you can just call outside the object
        without needing to reference rachelsObjectLiteral.  sounds like
        python's global.");
    }
};

rachelsObjectLiteral["objectHappiness"] = "really happy"

So as the object name announces, this is the Object Literal way to object creation. All of these things can be accessed via rachelsObjectLiteral.attribute, for example rachelsObjectLiteral.objectColor would refer to “red.” And a method is a function inside of an object. It’s hidden because you can’t call rachelsMethod without the object name. Also note that in an object literal construction, it’s COMMAS that go after each attribute (but not the final one), not semicolons.

And also note that I can add an attribute super easily here, e.g. "objecthappiness".

2

function objectConstructor (objectAttribute1, objectAttribute2) {
    this.objectAttribute1 = objectAttribute1;  # as someone helped me with this is comparable
    this.objectAttribute2 = objectAttribute2;  # to python's self.attributeName = attributeName
    this.objectMethod = function(parameter) {
        return parameter;
};

var constructee = new objectConstructor (27, "floppy");

I really like this method of object creation. Name the superstructure, give it the attributes its constructed objects will eventually have, and then make a var as a new version of that superstructure. It’s just so easy to construct objects once you’ve created the structure!

Next we’ve got what seems to be a sort of pared down version of the second method, an object which at first has no attributes and whose attributes are assigned with keys, one by one. This second type of Constructor-style reminds me a lot of Pythonic dicts:

3

var newThing = new Object();
newThing["attribute1"] = "happy go shiny";
newThing["attribute2"] = "here's the second one!";

A really small version of the method three is var objectName = {}; and attributes can be assigned in the same way, or with dot notation, à la objectName.attribute3 = "hooray!";.

Finally, we’ve got the prototype of objects. Once an object’s been created, if you want to add more attributes you can do as we did in example 1, AND you can use prototype like so!

function Task (taskName) {
    this.taskName = taskName;
};

var coding = new Task("writing Python");

Task.prototype.checkOver = function() {
    return "you did it right, right?";
};

coding.checkOver();

var cleaning = new Task("tidying");

cleaning.checkOver();

Prototyping is probably the most challenging piece of this language for me, and along with that, it’s likely one of the most powerful. Ok! I will be coming back to this post probably constantly, hopefully you find it useful too!

Bananalogies in Javascryptography

Have you all read Douglas Hofstadter’s beautiful Gödel, Escher, Bach: An Eternal Golden Braid? You should go get your copy. If you don’t have one yet, you can take one home for your very self here. I’ll wait. The internet always waits.

Ok! Remember the terrific inter-chapter dialogues between the Tortoise and Achilles? Remember the one about pushing and popping, meta-Genies, and the Majotaur, “Little Harmonic Labyrinth”? Page 103 in the 20th Anniversary edition. Hofstadter was something of a computer scientist (while being rather disinterested in programming itself), so it’s no surprise that the mathematics of this dialogue (and indeed of the entirety of the delightfully dense GEB) read like a computational theory problem wrapped up in a Lewis Carroll witticism (whom Hofstadter adores and references frequently in the book).

I’m getting lost in the book, as I so often do : ) but my point here, other than urging you to GO! GO! READ THIS BOOK! IT’S HARD AND THAT’S OK! is that javascript’s class inheritance reminds me just a bit of this airy idea of pushing and popping from world to world. Each class is its own world, and pushing from that class is another class that can only come from the initial one.

function Feline = (name, type) {
    this.name = name;
    this.type = type;
};

Now let’s add a method to this class:

Feline.prototype.infoPrint = function() {
    for (var i in Feline) {
        console.log(Feline.i);
    }
};

And now, let’s make a new thing altogether. Notice the third attribute:

function DSH = (name, type) {
    this.name = name;
    this.type = type;
    this.color = color;

And now! Since we know that Domestic Short Haired cats are a kind of Feline, let’s make it so officially, and actually CREATE an animal out of this!!

DSH.prototype = new Feline();

var morris = new DSH("Morris", "ornery", "buff and white");

Also notice that only objects created from constructor DSH will have the attribute color, but the regular Feline class will not. DSH is a push down from Feline, and divining objects from the constructor DSH will only give us specific DSHs, which have all the characteristics of Feline as well (though I believe those are specially mutable even after you’ve defined them, but more on that later, when I understand better too [which I am pretty sure can be strung into the metaphor of popping, perhaps?!] : ))!

So, go ye, and read of Gödel, Escher, Bach: An Eternal Golden Braid and tell me what beautiful mathematic or programmatic relation he makes you think of, and, likely, consider in a whole new way!

Last thing: once, on the train (a multi-day, cross-country trip), I had that book in my hand, waiting to get a morning coffee so I could sit and read it (I’ve still only read up to page ~130), and a gal came up to me and said “I read that book thirty years ago, and I’ve been reading it ever since.” Still the finest commendation for a book that I’ve ever heard.

Rabbit object constructor with nested function

EDIT: no longer private, because the notes are good and I thought back to them this morning, so, good enough for me! This is from Codecademy Introduction to Objects 1 25/33.
Private because a) it’s not my code and b) there’s no commentary but it’s important enough to log

function Rabbit(adjective) {
    this.adjective = adjective;
    this.describeMyself = function() {
        console.log("I am a " + this.adjective + " rabbit!");
    };
}

// now we can easily make all of our rabbits

var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");

rabbit1.describeMyself(); // called with constructed object, NOT constructor name.
rabbit2.describeMyself(); // constructedObject.internalMethod
rabbit3.describeMyself(); // output: "I am a sleepy rabbit!"

More JS Hobgobjects

Oh, wow, javascript object constructors. Cooooooooooool. Let’s dive right in, shall we?

function Expenses(AP,dollarsOut,frequency) {
    this.AP = AP;
    this.dollarsOut = dollarsOut;
    this.frequency = frequency;
    this.goodExpense = "maybe?";
};

var phone = new Expenses("Sprint Cellphone Bill", 160, "monthly")
var restaurants = new Expenses("Restaurant food out", 300, "monthly")

console.log("You spend " + restaurants.dollarsOut + " on " + restaurants.AP + ".")
console.log("Is " + phone.AP + " a good expense? Answer: " + phone.goodExpense)

Output:

You spend 300 on Restaurant food out.
Is Sprint Cellphone Bill a good expense? Answer: maybe?

To unpack this a bit, the constructor Expenses up there is defined up top with three attributes, which then makes the template creation of objects a SNAP. So phone and restaurants are whip-fast created. I can even make an attribute, like this.goodExpense, that’s not part of the callable constructor, but which every object created from it retains that defined attribute! AHHHH THAT IS SO COOL flail

And I can just access the attributes of these objects this easily! Seems magical. The this requirement of objects in JS is a little more approachable. Sorry for the flurry of posts – I just really, really want to get this course done, AND OBJECTS COMPLETELY UNDERSTOOD, so that I can move onto my next project which I am so so so excited for : )

Hobgobjects

I want to know OOP. I basically do, but I want to get the syntax all the way down and also ALSO be able to use them, which I’ve only done to the extent that I’ve copied fabulous OOP luminaries’ code. So far, I don’t have much to say, but it is just! so! important! that I make a note of what I learn when I learn it.

var functionName = function (parameter) {
    this.thing = newThing
}
var objectName = new Object();
objectName.methodName = "methodQuality";
objectName.functionName = functionName;  // this is what I'm having trouble understanding.

Hm. That’s.. that’s not really clear. the this piece of the object creation reminds me a bit of the confusing nature of self in Python. Is that a reasonable analogy?

Going to copy this piece from the codecademy lesson: “Then when we say objectName.functionName = functionName; (line 9), it means whenever we type objectName.functionName( ), this.thing in the functionName method will refer to objectName.methodName.” Maybe I just need to whisper that to myself mystically while sailing along on my bike. Yes, that must be the answer!*

*I’ll get there : )

For loops in Javascript

I learned this probably fifty lessons ago, BUT going through the blog I see I hadn’t noted it yet, and it’s just different enough from Python that I ought to at least make a note of it. It also addresses some of my thoughts from my first long-form Javascript post on the range function.

for (var i = 1; i <= 20; i++) {
    console.log(i)
}

That’s all! A bite-sized one today : )