//function express, return a object to var var anonymousGreet = function (){ console.log('hi'); } anonymousGreet(); //use () to invoke a function
function hoisting
1 2 3 4 5
anonymousGreet(); //error : anonymousGreet is undefined this line var anonymousGreet = function (){ //anonymousGreet is set to a function console.log('hi'); }
pass function as parameter
1 2 3 4 5 6 7 8
functionlog(a){ console.log(a); }
log(function (){ console.log('hi'); });
#4-36 By value and By reference
In js, primitives are by value
In js, objects(includes functions) are by reference
this.name = "updated c object"; console.log(this);//c object
var setname = function(newname){ this.name = newname;// the global object ,windows!!! // a lot of people think it's wrong } setname('updated again!!'); console.log(this); //c object with name : "updated c object" } } c.log();
tips avoiding weird this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
var c = { name:"the c object", log: function(){ var self = this; //save this(c object) address in var self
self.name = "updated c object"; console.log(self);
var setname = function(newname){ self.name = newname;// self point to the c objects } setname('updated again!!'); console.log(self); } } c.log();
4-38 Array-collection of anything
In javascript, array is typeless. You can put anything into it(Even a function = special object).
array contains everything
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var arr = [ 1, true, { name:'sam', phone:'0911111111' }, function (name){ var greeting = 'Hello '; console.log(greeting + name); }, "bello" ] arr[3](arr[2].name); // "Hello sam"
4-39 arguments and spreads
arguments keyword contains all the function arguments
arguments is array-like, not exactly regular array