js方法調用的四種模式
1、方法調用模式
1 function Persion() {
2 var name1 = "itcast",
3 age1 = 19,
4 show1 = function() {
5 console.log(this.name);
6 };
7
8 return {
9 age : age1,
10 name : name1,
11 show : show1
12 };
13 }
14
15 var p = new Persion();
16 p.show(); //在show方法中的this指向了p對象。
2、 函數調用模式
1 function add( a, b) {
2 this.result = a + b;
3 }
4
5 add( 3, 9 ); //此方法執行的時候,this指向了window
6
7 console.log(result);
3、構造器調用模式
1 function Persion(){
2 this.name = "123";
3 this.age = 19;
4 this.show = function(){
5 console.log(this.name);
6 };
7 }
8
9 var p = new Persion();
10 p.show();// 在show方法中方法this,指向了p對象執行個體。
4、call 和 apply調用模式
1 function add(a,b){
2 this.result = a + b;s
3 }
4
5 var p = {}; //定義一個空對象。
6 add.call(p,3,4); //在這個方法調用的時候,this指向了p
7 console.log(p.result);
8
9 //apply和call是一樣的用法,隻不過apply第二個參數用數組進行傳遞。
變量提升:函數執行之前,會先将函數中所有的變量,挪到最前面去聲明。
函數名提升: script中腳本,在執行之前,會先把腳本中的所有的函數先進行編譯解析,然後執行普通的js代碼。