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