1 <script > 2 //this知識 單詞知識:property:屬性 prototype:原型 3 //*Q:什么是this? 4 //*A:所有函數內部都有一個this,任何函數本質上都是通過某個對象來調用的,如果沒有直接指定就是window 5 //* 它的值是調用函數的當前對象 6 //*Q:如何確定this的值 7 //*A:test:window 8 // p.test():p對象 9 // new test():新創建的對象 10 // p.call(obj):obj 11 12 function Person(color) { 13 console.log(this) 14 this.color = color; 15 this.getColor = function () { 16 console.log(this) 17 return this.color; 18 }; 19 this.setColor = function (color) { 20 console.log(this) 21 this.color = color; 22 }; 23 } 24 25 Person("red"); //this是誰? window 26 27 var p = new Person("yello"); //this是誰? p 28 29 p.getColor(); //this是誰? p 30 31 var obj = {}; 32 p.setColor.call(obj, "black"); //this是誰? obj 33 34 var test = p.setColor; 35 test(); //this是誰? window 36 37 function fun1() { 38 function fun2() { 39 console.log(this); 40 } 41 42 fun2(); //this是誰? window 43 } 44 fun1(); 45 46 //JS關于加分號問題‘ 47 //js一條語句后面可以不加分號 48 //是否加分號是編碼風格問題,沒有應該或不應該,只有你喜不喜歡 49 //但在以下情況下不加分號會出現問題,要求需要在前面加一個分號 50 //小括號開頭的前一條語句 51 //中括號開頭的前一條語句 52 var a=3 53 ;(function () {//匿名函數自調用前面如果不加分號會出現錯誤,所以需要在前面加上一個括號 54 55 })() 56 57 var b=4 58 ;[1,2].forEach(function () {//這里在IDE上不會顯示紅線,但在運行中會出現編譯錯誤,所以這里也要加一個分號,最好是加在一條語句的前面 59 60 }) 61 /* 62 編譯器的錯誤理解:var b=4[1,2].forEach(function () {//就會報undefined 63 }) 64 */ 65 </script>
?