简单的函数实现
function checkName() {
// body...
}
function checkEmail() {
// body...
}
function checkPassword() {
// body...
}
对象中的实现
let CheckObject = {
checkName: function () {},
checkEmail: function () {},
checkPassword: function () {},
};
let CheckObject1 = function () {};
CheckObject1.checkName = function () {};
CheckObject1.checkEmail = function () {};
CheckObject1.checkPassword = function () {};
对象实现的改进
let CheckObject2 = function () {
return {
checkName: function () {
return this;
},
checkEmail: function () {
return this;
},
checkPassword: function () {
return this;
},
}
};
let a = CheckObject2();
a.checkEmail();
类的实现
let CheckObject3 = function () {
this.checkName = function () {};
this.checkEmail = function () {};
this.checkPassword = function () {};
};
let a3 = new CheckObject3();
a3.checkEmail();
类实现的改进,将方法装到原型上
let CheckObject4 = function () {};
CheckObject4.prototype.checkName = function () {};
CheckObject4.prototype.checkEmail = function () {};
CheckObject4.prototype.checkPassword = function () {};
let CheckObject5 = function () {};
CheckObject5.prototype = {
checkName: function () {},
checkEmail: function () {},
checkPassword: function () {}
};
let a5 = new CheckObject5();
a5.checkName();
a5.checkEmail();
a5.checkPassword();
链式调用
let CheckObject6 = function () {
};
CheckObject6.prototype = {
checkName: function () {
return this;
},
checkEmail: function () {
return this;
},
checkPassword: function () {
return this;
}
};
let a6 = new CheckObject6();
a6.checkName().checkEmail().checkPassword();
在Function原型上添加方法
Function.prototype.addMethod = function (name, fn) {
this[name] = fn;
};
// let methods = new Function();
let methods = function () {};
methods.addMethod('checkName', function () {});
methods.addMethod('checkEmail', function () {});
methods.addMethod('checkPassword', function () {});
methods.checkName();
methods.checkEmail();
methods.checkPassword();
链式添加,以及链式调用
Function.prototype.addMethod = function (name, fn) {
this[name] = fn;
return this;
};
let methods1 = function () {};
methods1.addMethod('checkName', function () {
return this;
}).addMethod('checkEmail', function () {
return this;
});
methods1.checkName().checkEmail();
装载到原型上
Function.prototype.addMethod = function (name, fn) {
this.prototype[name] = fn;
};
let Methods = function () {};
Methods.addMethod('checkName', function () {
}).addMethod('checkEmail', function () {
});
let m = new Methods();
m.checkName();