如何在 javascript 中从字符串调用私有函数
How to call a private function from a string in javascript?
我正在构建一个小的"Validate"对象,它基本上公开了一个验证方法,并获取一个元素和一个验证器数组的id,然后返回true或false。
基本上这就是我想要实现的目标
var Validator = function() {
var no_digits = function( el ) {
return true;
}
var no_uppercase_letters = function( el ) {
return true;
}
return {
validate: function( element_id, validators ) {
//here i would like to iterate on the validators array and for each
//element of the array i would like to check if a function of the same name
// exist and call that function passing the element
}
}
}();
然后这样称呼它
var element_valid = Validator.validate( 'myid', [ "no_digits", "no_uppercase_letters"] );
其中第二个参数是我想调用的验证器数组。
关于一个好的面向对象的方法有什么建议吗?我想将验证函数保持私有,否则我可以这样做
var Validator = function() {
return {
validate: function(element_id, validators) {
console.log(this);
this[validators]();
// Validator[validators](element_id);
},
no_digits: function(el) {
alert('hi');
return true;
},
no_uppercase_letters: function(el) {
return true;
}
}
}();
但我宁愿将no_gits no_uppercase_letters函数保密
var element_valid = Validator.validate('myid', "no_digits");
var valdiate = (function() {
var _p={};//toss all private members into a single object.
_p.list=[];
_p.init=function(){
_p.list=[];
};
var noDigits = function() {
};
//public members. use "this" to reference object followed by the method.
//however valdiate._p.list won't be accessible to the global scope
return {
check: function() {
noDigits();
},
fnNaMe1:function(){
_p.init();
},
fnName2:function(){
return _p.list.slice(0);//return a clone
}
};
})();
它被称为"模块模式"。这种模式在 JavaScript 中通常简称为"封装"。闭包是另一种可能,但更具体地说,在这种情况下,它纯粹是封装。
封装只是意味着您将某些成员设为私有。在这种情况下,什么是私有的?在这种情况下,noDigits
变量是私有的。
这种方法行得通吗?
jsFiddle在这里:http://jsfiddle.net/FranWahl/KZKwA/玩。
请注意,我没有实现任何实际的验证,但基本框架确实执行了。
var Validator = function() {
return {
validate: function(element_id, validators) {
for (var i = 0; i < validators.length; i++) {
var result = validators[i](element_id);
alert(result);
// record results... or do something else with it or break; etc...
}
}
}
}();
var no_digits = function(theValue) {
// validate no digits are in the given value....
if(theValue === '1')
{
return true;
}
else
{
return false;
}
};
var no_uppercase_letters = function(theValue) {
// validate no uppercase letters are in this value...
if(theValue === '4')
{
return true;
}
else
{
return false;
}
};
// I used variables to store the methods but feel free to declare the methods inline instead...
var element_valid = Validator.validate('4', [no_digits , no_uppercase_letters]);
相关文章:
- 如何从模块链中调用函数.导出到节点中
- 调用函数内部的函数
- 在javascript中调用c函数
- DropDownListFor赢得't在更改时调用函数
- Javascript页面调用函数
- 在动画结束之前调用函数
- 允许父窗口在其不同域的子iframe上调用函数
- 运行Infinite Scroll后调用函数时出现问题
- JavaScript:在调用函数的文本输入上按enter键
- 使用大括号和不使用bracs调用函数的区别
- javascript在事件上调用函数
- 从index.html调用函数,该函数无限循环
- 从带参数的字符串变量调用函数中的函数
- 为什么 JS 不在滚动时调用函数
- 是否可以在不更改上下文的情况下调用函数.apply
- 如何在ES6类中使用参数调用函数
- AngularJS:调用函数时编号不更新
- JavaScript中的立即调用函数表达式(IIFE)-传递jQuery
- 在JavaScript中调用函数时自定义此选项
- 调用函数中声明的变量