function indexOf(haystack, needle) {
var i = 0,
max = haystack.length;
for (; i < max; i += 1) {
if (haystack[i] === needle) {
return i;
}
}
return -1;
}
//通过赋值的方式,将上面所有的细节都隐藏了
myarray = {
isArray: isArray,
indexOf: indexOf,
inArray: indexOf
};
} ());
//测试代码
console.log(myarray.isArray([1, 2])); // true
console.log(myarray.isArray({ 0: 1 })); // false
console.log(myarray.indexOf(["a", "b", "z"], "z")); // 2
console.log(myarray.inArray(["a", "b", "z"], "z")); // 2
myarray.indexOf = null;
console.log(myarray.inArray(["a", "b", "z"], "z")); // 2
模式5:链模式
链模式可以你连续可以调用一个对象的方法,比如obj.add(1).remove(2).delete(4).add(2)这样的形式,其实现思路非常简单,就是将this原样返回。代码如下:
复制代码 代码如下:
var obj = {
value: 1,
increment: function () {
this.value += 1;
return this;
},
add: function (v) {
this.value += v;
return this;
},
shout: function () {
console.log(this.value);
}
};
// 链方法调用
obj.increment().add(3).shout(); // 5
// 也可以单独一个一个调用
obj.increment();
obj.add(3);
obj.shout();
总结
本篇是对象创建模式的上篇,敬请期待明天的下篇。
您可能感兴趣的文章: