[url=http://www.1sucai.cn/article/29472.htm]深入理解JavaScript系列(3):全面解析Module模式[/url]》里的Module模式有点类似,但是不是return的方式,而是在外部先声明一个变量,然后在内部给变量赋值公有方法。代码如下:
var myarray;
(function () {
var astr = "[object Array]",
toString = Object.prototype.toString;
function isArray(a) {
return toString.call(a) === astr;
}
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
[b]模式5:链模式[/b]
链模式可以你连续可以调用一个对象的方法,比如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();
[b]总结[/b]
本篇是对象创建模式的上篇,敬请期待明天的下篇。