@GivenCui
2016-08-11T14:38:29.000000Z
字数 2403
阅读 813
JavaScript设计模式
创建了全局变量, 会污染全局
// 1.1 函数声明function checkName () {console.log("验证用户名");}function checkEmail () {console.log("验证邮箱");}function checkPassword () {console.log("验证密码");}// 1.2 函数表达式var checkName = function () {console.log("验证用户名");};var checkEmail = function () {console.log("验证邮箱");};var checkPassword = function () {console.log("验证密码");};
只是一个单例, 不能复制多份
// 变为对象中的方法var checkObject = {checkName : function () {console.log("验证用户名");},checkEmail : function () {console.log("验证邮箱");},checkPassword : function () {console.log("验证密码");}};
// 变为函数(特殊的对象)的方法var checkObjec = function () {};checkObject.checkName = function () {console.log("验证用户名");};checkObject.checkEmail = function () {console.log("验证邮箱");};checkObject.checkPassword = function () {console.log("验证密码");};
新对象与函数之间没有关系
var checkObject = function () {return {checkName : function () {console.log("验证用户名");return this;},checkEmail : function () {console.log("验证邮箱");return this;},checkPassword : function () {console.log("验证密码");return this;}};};// 调用var a = checkObject();a.checkName().checkEmail().checkPassword();
比较完美的方案
// 构造函数var CheckObject = function () {};CheckObject.prototype = {checkName : function () {console.log("验证用户名");return this;},checkEmail : function () {console.log("验证邮箱");return this;},checkPassword : function () {console.log("验证密码");return this;}};// 调用var a = new CheckObject();a.checkName().checkEmail().checkPassword();
不能直接向Funtction的原型中添加方法, 会污染
编写一个插件管理器
// 函数式调用方法// 插件管理器Function.prototype.addMethod = function (name, fn) {this[name] = fn; // 在函数上调用return this;};var m1 = function () {}; // function是Function的实例m1.addMethod("checkName", function () {console.log("验证用户名");return this;}).addMethod("checkEmail", function () {console.log("验证邮箱");return this;}).addMethod("checkPassword", function () {console.log("验证密码");return this;});// 调用m1.checkName().checkEmail().checkPassword();
// 类式调用方法// 插件内部实现不同Function.prototype.addMethod = function (name,fn) {this.prototype[name] = fn; // 添加在了原型上,所有类式调用return this;};var M1 = function () {}; // function是Function的实例M1.addMethod("checkName", function () {console.log("验证用户名");return this;}).addMethod("checkEmail", function () {console.log("验证邮箱");return this;}).addMethod("checkPassword", function () {console.log("验证密码");return this;});// 调用var a = new M1();a.checkName().checkEmail().checkPassword();var b = new M1();b.checkName().checkEmail().checkPassword();