Javascript objects

From wikinotes
Revision as of 23:07, 23 May 2021 by Will (talk | contribs) (→‎Prototype Objects)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Objects are a core concept of javascript.
They behave like an associative array, but they are also the foundation for classes.

Documentation

official docs https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects

Objects

// emtpy object
var obj = {}
var obj = new Object()

obj['key'] = 'value'

Defined similarly to a struct, or a dictionary you can bind methods to.

const student = {
    name: 'Alex',
    age: 32,
    siblings: ['Jessie', 'Amelia'],
    skills: {
        drawing: 9,
    },
    speak: function() {
        console.log('hello')
    },
}

student.name
student.speak()
student.
student.siblings[0]
student.skills.drawing
student['skills']['drawing']

Objects can also be used in place of classes.

function Student(name, age) {
    this.name = name
    this.age = age
}

Prototype Objects

Prototype objects are even more similar to classes.
They can be parametrized, and have access to the arguments they are created from.

function Person(firstname, lastname)
    this.firstname = firstname
    this.lastname = lastname
}

let person = new Person('Luke', 'Skywalker')
let copy = Person.create(person)

person.constructor  // returns Person
person.constructor('Leia', 'Skywalker')

You can modify the prototype object after creation.

Person.prototype.speak = function () { ... }