JavaScript Objects

object topics

  • everything is an object*
  • variable names
  • instantiation
  • built-in properties
  • object.create
  • emulating data types
  • objects vs. arrays
  • observables

"JavaScript is designed on a simple object-based paradigm"

"an object is a collection of properties"

"a property is an association between a name and a value"

almost everything is an object in JavaScript

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

not objects

  • null
  • undefined

what does that mean?

variable names

rules

  • start with a letter, underscore or dollar sign
  • numbers allowed after the first character
  • case sensitive
  • Unicode letters such as å and ü are allowed*
  • effectively no length rules

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals

*starting in 2000 with JavaScript 1.5

good

count = 10;

innerColor = "red";

$thing1

_thing2

bad

hello-fish

1fish

2fish

~fish

!fish

#fish

@fish

%fish

^fish

&fish

*fish

-fish

etc. (which is also bad)

creating objects

object initializers

a.k.a. "literal notation"

var airplane = {
    make: "Cessna",
    model: "Turbo Stationair",
    "tail number": "N4835F"
};
    
    
> airplane.make;
'Cessna'

> airplane["tail number"];
'N4835F'

"WAIT, YOU LIED TO ME!"

> var airplane = {
    make: "Cessna",
    model: "Turbo Stationair",
    "tail number": "N4835F"
};
    
    
> airplane.make;
'Cessna'

> airplane["tail number"];
'N4835F'

dot and key notation

  • define a constructor function
    • first letter is upper case by convention
  • instantiate with the new keyword

a.k.a. "constructors"

constructors

constructor function

> function Airplane (make, model, tailNumber) {
    this.make = make;
    this.model = model;
    this.tailNumber = tailNumber;
}
    
> var betsy = new Airplane('Cessna', 'Stationaire', 'N4835F');

> betsy.make;
'Cessna'

> betsy.tailNumber];
'N4835F'
> function Airplane (make, model, tailNumber) {
    if(!(this instanceof Airplane)) { 
        return new Airplane(make, model, tailNumber); 
    }   
    this.make = make;
    this.model = model;
    this.tailNumber = tailNumber;
}
    
> var betsy = new Airplane('Cessna', 'Stationaire', 'N4835F');

> betsy.make;
'Cessna'

> betsy.tailNumber;
'N4835F'

new safe

use object literal notation whenever possible

Next Up... Cory

JavaScript Objects

By Bruce Campbell

JavaScript Objects

Section 1 of a 3 section training on JavaScript objects

  • 933