Objects Flashcards
Object
stores any number of values associated with string “keys”
var (name) = {
(key) : (value),
(key2) : (value2)
}
(name).(key) or (name)[“(key with spaces)”]
Create an object, ‘me’, with the key of “name” with your name as a string. Add to the ‘me’ object a key of “age” and set it to your age, not as a string, but a number.
var me = { name: "Randy", age: 25 };
Method
a function that is a property of an object
(object).(key)((arg)) —> console.log
this
- refers to the global object, window
- to be used only as a method
On ‘andrew’ and ‘ryan’, set the ‘greet’ method as the ‘genericGreet’ function.
var genericGreet = function() { return "Hello, my name is " + this.name; }
var andrew = { name: "Andrew" }
var ryan = { name: "Ryan" }
var genericGreet = function() { return "Hello, my name is " + this.name; }
var andrew = { name: "Andrew", greet: genericGreet }
var ryan = { name: "Ryan", greet: genericGreet }
Call vs. Apply
- call takes any # of args and puts it in context of this
- apply strictly takes an array of args
Set the ‘greeting’ variable, by using the ‘genericGreet’ function in the context of ‘andrew’ with the array of arguments, ‘args1’.
var genericGreet = function(name, mood) { name = name || "you"; mood = mood || "good"; return "Hello " + name + ", my name is " + this.name + " and I am in a " + mood + " mood!"; }
var andrew = { name: "Andrew" }
var args1 = [“Michael”, “awesome”, “:)”];
var greeting = genericGreet;
var greeting = genericGreet.apply(andrew, args1);
if “name” is false or undefined, then || = “or” operator and uses “you”
Prototype
an object that provides keys and values for another object
Object Oriented Programming
programming based around creating and using objects
Constructor Function
- special function for creating and initializing a new object
- always capitalize first letter
new
creates new object, passes it to constructor function, and returns it
Modify the ‘Car’ constructor function so that it takes an argument for its model and set its ‘model’ to the model passed in from the argument.
var carPrototype = {
model: “generic”,
currentGear: 0,
increaseGear: function() {
this.currentGear ++;
},
decreaseGear: function() {
this.currentGear–;
}
}
function Car() {
}
function Car(model) { this.model = model; }
After the ‘Car’ constructor function, modify the Car’s prototype to be the ‘carPrototype’.
function Car(model) { this.model = model; }
function Car(model) { this.model = model; Car.prototype = carPrototype; }
Modify the Car’s prototype to have ‘wheels’ set to 4.
function Car(model) { this.model = model; Car.prototype = carPrototype; }
function Car(model) { this.model = model; Car.prototype = carPrototype; Car.prototype.wheels = 4; }
What are the values of mittens.name and mittens.legs after this code executes?
function Cat (name) {
this.name = name; this.ears = 2;
}
var mittens = new Cat(“Sir Mittens”);
Cat.prototype.legs = 4;
mittens. name === “Sir Mittens”;
mittens. legs = 4;