console.log(myFunc);
console.log(myFunc(3, 6));
function myFunc(a, b) {
return a + b;
}
-----------------------------------
// 執行結果//function myFunc(a, b) {
return a + b;
}
//9
匿名表達式 (Function Expressions without Function Name)>>
先宣告一個變數,再定義一個函數內容放到該變數裡。
此方式定義的函數實際上是匿名函數 (a function without a name),將函數定義的主體,存在你定義的變數裡。
變數名稱不等於函數名稱。
不具 Hoisting 提升效果。
console.log(myFunc);
// console.log(myFunc(3, 6)); // TypeError: myFunc is not a function
let myFunc = function (a, b) {
return a + b;
};
console.log(myFunc);
console.log(myFunc(3, 6));
-----------------------------------
//執行結果
//undefined
//ƒ (a, b) {
return a + b;
}
//9
具名表達式 (Function Expressions / Function Name)>>
和「匿名表達式」相似,差別在定義函數內容時,有給予一個函數名稱 (Function name)。
定義的函數印出來會有函數名稱(不等於變數名稱)。
但無法直接透過該函數名稱呼叫。
不具 Hoisting 提升效果。
console.log(myFunc);
// console.log(myFunc(3, 6)); // TypeError: myFunc is not a function
var myFunc = function aaa(a, b) {
return a + b;
};
console.log(myFunc);
console.log(myFunc(3, 6));
// console.log(aaa); // ReferenceError: aaa is not defined
-----------------------------------
//執行結果
//undefined
//ƒ aaa(a, b) {
return a + b;
}
//9
建構子式 (Function Constructor)>>
說到建構子我們不得不提 new 這個Keyword,因為提到new 我們就要有個概念: 我們正在建立物件!
console.log(myFunc);
// console.log(myFunc(3, 6)); // TypeError: myFunc is not a function
var myFunc = new Function("a", "b", "return a + b");
console.log(myFunc);
console.log(myFunc(3, 6));
-----------------------------------
//執行結果 // undefined
// ƒ anonymous(a,b) {
return a + b
}
//9
function User() {
this.name = 'Bob';
}
function AnotherUser() {
this.name = 'Hugo';
}
var user1 = new User();
var user2 = new AnotherUser();
console.log(user1.name);
console.log(user2.name);
//顯示結果Bob
Hugo
This :Arrow Function內 結構功能
//-----一般函式
function User() {
this.name = "Bob";
return this;
}
console.log(this.name);
//-----箭頭函式()=>{
this.name ="It is Arrow Functions";
}
console.log(this.name);
console.log(typeof this.name);
//顯示結果(空物件)
It is Arrow Functions
string
This 提取Arrow Function內部值
// Arrow function 1
()=>{
this.name ="It is Arrow Functions";
}
console.log(this.name);
console.log(typeof this.name);
//顯示結果
//It is Arrow Functions
//It is Arrow Functions
//string
箭頭函數(Arrow Functions) — this是定義時的對象, 不是在使用的物件。
傳統Function語法 — this是使用、呼叫(call)時的對象。
用setInterval 將一般函式this 物件p帶出
function Person() {
// Person() 建構式將 this 定義為它自己的一個實體
this.agegrowing = 0;
setInterval(function growingUp() {
// 在非嚴格模式stric mode下, growUp() 函式把 this 定義為全域物件
// (因為那是 growingUp()執行的所在),
// 與 Person() 建構式所定義的 this 有所不同this.agegrowing++;
}, 3000);
}
// 在全域做另一個物件 p
var p = new Person();
console.log(p);
在 ECMAScript 3/5 裡面,this 可透過指派 this 值。
function Person() {
var me = this;
me.age = 0;
setInterval(function growUp() {
// 這個 callback 參考 `self` 變數,為預期中的物件。
mee.age++;
}, 1000);
}
透過 bind 函式來綁定 this 變數到指定函式(上面為例,就是 growingUp() 函式)。