Functions and Object
Object
Collection of values, can have properties or method (Still a function but called a method when its sitting in an object)
var person = new Object();
//Properties:
person["firstname"] = "Tony"
person["lastname"] = "Alicea"
var firstNameProperty = "firstname"
console.log(person[firstNameProperty]); - Called Computed member access
console.log(person.firstname) - Called member access
person.address = new Object()
person.address.street = "111 Main St."
console.log(person.address.street);
console.log(person.["address"]].["street"]);
Object Literals
Object Literals
var person = {} is the same as var person = new Object();
Not an operator, Javascript Engine assumes it is creating an object when it sees {}
Can initialise properties and methods:
var person = {
firstname: 'Tony'
lastname: 'Alicea'
}
Functions are Object
First class function:
- Everything you can do with other types you can do with functions
- Assign them to variables, pass them around, create them on the fly
Function: special type of object, resides in memory
- Can attached properties and method or function to a function
- Some hidden special properties
- NAME (Optional - can be anonymous)
- CODE (Where the actual lines of code you wrote sits) : It is Invocable ()
Example of adding a property to a function:
function greet(name) { //NAME : greet //CODE: console.log('hi')
console.log('Hi');
}
greet.language = 'english'
console.log(greet), we get the text of the function that we wrote:
function greet(name) {
console.log('Hi');
}
if we access the property in the function:
console.log(greet.language), we get: 'english'