函數定義方式
1 function 調用在前和在後無影響
function ***() {
}
2 函數表達式(匿名函數) 需要先定義再調用
var fn = function() { }
3 new Function()
// Function裏面參數都是字符串格式
var f = new Function('a','b','console.log(a+b)');
f(2,5);
f.index = 10;
console.log(f.__proto__ === Function.prototype); //true
console.log(f instanceof Object);
console.log(f.index);
所有函數都是Function的實例,函數也是對象
Function ---------> Function.prototype
函數的調用方式和this
1 普通函數調用
普通函數調用 則函數中this === window
function fn() {
console.log(this); //
console.log('hello everyone');
}
fn(); // fn.call() 普通函數調用 則函數中this === window
2 對象調用
對象調用 函數中this === 該對象
var obj = {
sayHello: function() {
console.log(this);
console.log('hi');
}
}
obj.sayHello(); // 對象調用 函數中this === 該對象
3 構造函數調用
構造函數調用 this === 實例對象
function Student() {
}
new Student(); // 構造函數調用 this === 實例對象
4 事件觸發的函數
通過事件觸發 this指的是綁定事件對象
btn.onclick = fun // 通過事件觸發 this指的是綁定事件對象
5 定時器函數
定時器函數,函數中this === window
setInterval(function() {
console.log(this); // window
},1000);
6 立即執行函數
立即執行函數中this === window
(function() {
console.log(this);//立即執行函數中this === window
console.log(11);
})();