下面我们结合前面学习的内容, 写一个 Map
1. 定义一个 自执行函数(闭包)
自执行函数(闭包)的定义有三种: !function(形参列表){}(实参列表)
、(function(形参列表){}(实参列表))
、(function(){})()
。
我们选用这种 (function(形参列表){}(实参列表))
(function (){
}())
2. 定义一个名为 map
的函数, 并返回
(function (){
function map() {
}
return map
}())
3. 在map
的函数里定一个对象变量 container
(function (){
function map() {
this.container = {
}
}
return map
}())
4. 把整个 自执行函数(闭包)
赋值给一个变量 Map
var Map = (function (){
function map() {
this.container = {
}
}
return map
}())
5. 在 map
函数的原型链上扩展
var Map = (function (){
function map() {
this.container = {
}
}
map.prototype.xxx = function () {
}
return map
}())
- 添加函数
isBlank
, 用于校验字符串是否为空, 如果为数字则不校验
function isBlank(value){
if (typeof value === "number") return false
var reg = /^[ ]+$/
return value === undefined || value === "" || value == null || reg.test(value)
}
- 在原型链上添加
put
方法
/**
* 根据 key 存放数据
*/
map.prototype.put = function (key, value) {
if (isBlank(key)) throw new Error('Please input key.')
this.container[key] = value
}
- 在原型链上添加
get
方法
/**
* 根据 key 获取数据
*/
map.prototype.get = function (key) {
if (isBlank(key)) throw new Error('Please input key.')
return this.container[key] || null
}
- 在原型链上添加
remove
方法
/**
* 根据 key 删除数据
*/
map.prototype.remove = function (key