# **apply 和 call**
* * * * *
對(duì)于 `API` 的使用,例如:`obj.hasOwnProperty(key)` 這類 `API` 就需要使用 `apply` 和 `call` 的第一個(gè)參數(shù),指定 `this`。
```
var LimitableMap = function (limit = 10) {
this.limit = limit
this.map = {}
this.keys = []
}
var hasOwnProperty = Object.prototype.hasOwnProperty
LimitableMap.prototype.set = function (key, value) {
var map = this.map
var keys = this.keys
// 如果在map自身屬性上沒(méi)有key
if (!hasOwnProperty.call(map, key)) {
// 如果保存的key等于給定的限制值
if (keys.length === this.limit) {
var shiftKey = keys.shift()
delete map[shiftKey]
}
// 把設(shè)置的key值保存在keys數(shù)組里
keys.push(key)
}
// 經(jīng)過(guò)上面判斷刪除值之后就可以添加新值了
map[key] = value
}
LimitableMap.prototype.get = function (key) {
return this.map[key]
}
module.exports = LimitableMap
```
類似上面代碼中的 `object.hasOwnProperty`,`object` 就是 `this`,所以需要在 `apply` 或者 `call` 中指定 `this` 參數(shù)。
- ES6
- ES6字段轉(zhuǎn)換小技巧
- 聲明變量
- 函數(shù)
- 遞歸函數(shù)
- 函數(shù)聲明和函數(shù)表達(dá)式
- 前端環(huán)境配置
- VScode
- VScode設(shè)置選項(xiàng)
- 遍歷
- 遍歷目錄
- 遞歸算法
- 遍歷算法
- 遍歷引用類型
- 異步編程
- 函數(shù)返回值
- 遍歷數(shù)組(異步)
- JS特殊值(args、this、require...)
- arguments
- 數(shù)據(jù)結(jié)構(gòu)與算法
- 扁平化數(shù)據(jù)轉(zhuǎn)樹狀數(shù)據(jù)(數(shù)組型)
- 扁平化數(shù)據(jù)轉(zhuǎn)樹狀數(shù)據(jù)(對(duì)象型)
- 嚴(yán)格模式
- 嚴(yán)格模式下的this
- JavaScript
- 內(nèi)置類型
- this
- typeof 操作符
- 原型與原型鏈
- 執(zhí)行上下文棧
- apply和call
