iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 19
0
自我挑戰組

我在繡房繡小主常服的日子-- 初入前端工程師的第一個小挑戰系列 第 19

[19] IDKJS - Function Invocation

Invoke

Function被定義(defined)時,在function裡的code並不會被執行,
Function被調用(invoked)時,在function裡的code會被執行。
一般會使用call a function而不是 invoke a function,
但是JavaScript中可以不用call 就invoke a function。

Invoking a Function as a Function

function add(x) {
  return x + 2;
};
add(2);
window.add(2);

add不屬於任何的object,
但是JavaScript有一個預設的全域物件 (global object),
在HTML page中,global object就是自身HTML page,
所以add這個function屬於HTML page,
而在瀏覽器中則是瀏覽器的window,
意旨add是window的function,
add()window.add()為同一個function。

this

在JavaScript中,this代表了擁有當前code的那個object
在function中的this,代表了擁有function的那個object

function add() {
  return this;
};
console.log(add()); // Window

add()屬於global object,window,所以這邊的this指的是window。

Invoking a Function as a Method

在JavaScript中,function也可以被定義成為object method:

var me = {
  name: 'Azer',
  age: 18,
  introduce: function() {
    return "My name is " + this.name + ", I'm " + this.age + " years old.";    
  }
}

me.introduce(); //My name is Azer, I'm 18 years old.

在這之中introduce是屬於me這個object的一個function,
在前面有提到說在function中的this,代表了擁有function的那個object
在這邊指的是me

var me = {
  name: 'Azer',
  age: 18,
  introduce: function() {
    return this; 
  }
}
me.introduce(); // {name: "Azer", age: 18, introduce: ƒ}

上一篇
[18] IDKJS - Defined function
下一篇
[20] IDKJS - Function call & apply
系列文
我在繡房繡小主常服的日子-- 初入前端工程師的第一個小挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言