DAY 8
1
Modern Web

# 強型闖入DenoLand[7] - TS基礎系列之函式宣告(2)

## What is "This"?

``````//...
private \$length = 0;
private \$memory = array();
function printList(){
if(\$this->length ==0){
return 0;
}
else{
while(true){
print_r(\$this->memory[\$currentNode]);
\$currentNode = \$this->memory[\$currentNode]->getNext();
if(\$currentNode === "nullPtr"){
break;
}
}
print "<br>";
}
}
//...
}
//...
``````

``````const returnYourName = function(){
return this.name;
}
const Ian = {
name: 'Ian',
whatYourName: returnYourName
}
const Peter = {
name: 'Peter',
whatYourName: returnYourName
}
console.log(Ian.whatYourName()) //Ian
console.log(Peter.whatYourName()) //Peter
``````

``````const returnYourName = function(){
return this.name;
}
const returnThis = function(){
return this.name;
}
const Ian = {
name: 'Ian',
whatYourName: returnYourName,
returnThis: returnThis
}
console.log(Ian.returnThis()) //Ian
``````

## call(), apply(), bind()

``````let sum = function(para1, para2){
return para1 + para2;
}
``````

``````sum(1,2); //3
``````

### bind()

``````function sum(para1:number,para2:number) {
console.log(para1 + para2,this)
}

const sumX = sum.bind('Hello')
sumX(1,2)
``````

``````3, Hello
``````

### apply() and call()

`bind()` 不同， `apply()``call()` 只需要在呼叫函式時加在後方：

``````sum.call('Ian', 1, 2) // Ian 1 2
sum.apply('Peter', [1, 2]) // Peter 1 2
``````

## 箭頭函式

``````()=>{
console.log("Hello, world!")
}
let sum = (para1: number, para2: number)=>{
return para1 + para2;
}
let result = sum()
``````

## 目前遇到的問題

• 全域下， `this` 應該要是 `window` 而不是 `undefined`
• 一直噴以下錯誤：
``````TS2683 [ERROR]: 'this' implicitly has type 'any' because it does not have a type annotation.
return this.name;
``````