---
description: 新增方法, this 就是傳進來 Array/Object... ; 要 return this 才能有 method chaining
---

# Prototype

if you want to add a method call "last" in Array, it will return the last element. If there are no elements in the array, it should return -1.

[2619. Array Prototype Last](https://leetcode.com/problems/array-prototype-last/)

```javascript
Array.prototype.last = function() {
    if(this.length === 0){
        return -1
    }
    return this[this.length-1]
    // return this.pop() 也可以
};
```

以下兩個基本上一樣



```javascript
// 1
class Calculator {
    /** 
     * @param {number} value
     */
    constructor(value) {
        this.callue = value
    }
    
    /** 
     * @param {number} value
     * @return {Calculator}
     */
    add(value){
        this.calculation += value;
        // 有 return this 才能 Calculator(10).add(5)
        return this;
    }
    
}


// 2
function Calculator(value) {
    this.value = value
}
Calculator.prototype.add =  function(value) {
}
```
