为什么原型中的javascript函数返回true或false
why my javascript function inside prototype return true or false
我有一个模块。我所做的是,当我在构造函数内创建对象func
的新实例时,模块内的函数会自动被调用。如果b为true,则func()
返回true,否则返回false。但是,它返回对象,即Module
为什么
var Module = function () { this.func() };
Module.prototype = function () {
var b = true;
func = function() {
if (b) {
return true;
}
return false;
};
return {
func: func
}
}();
console.log(new Module());
当我停止在构造函数内调用anyMobile()
函数,并创建IsMobile
的新实例,然后像下面这样调用anyMobile()
时,它确实返回true或false。
var m = new Module();
m.func(); //Works
因为这个-
return {
func: func
}
要公开访问的anyMobile是持有功能的CCD_ 7。
如果您改为执行func: func()
(现在这将是一个返回布尔值的函数调用),它应该可以工作!
查看这里漂亮地解释的概念
示例中的第一行是声明一个充当构造函数的函数。
var IsMobile = function () { this.anyMobile() };
当您调用新的IsMobile()时
- 使用IsMobile.prototype创建一个新对象OBJ作为其proto对象(以继承在IsMobile.prototype上定义的属性)
- 调用构造函数IsMobile时将此绑定到OBJ
- 如果构造函数返回对象,则返回该对象,否则返回OBJ
在您的情况下,在构造函数代码中调用anyMobile()方法,但忽略返回值。
我建议您修改代码,不要每次都创建新的IsMobile对象,如下所示:
IsMobile = function () {
var android = function() {
return navigator.userAgent.match(/Android/i);
},
blackBerry = function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS = function() {
return navigator.userAgent.match(/iPhone/i);
},
windows = function() {
return navigator.userAgent.match(/IEMobile/i);
},
anyMobile = function() {
if (android() || blackBerry() || iOS() || windows()) {
return true;
}
return false;
};
return anyMobile;
}();
console.log(IsMobile());
此外,由于navigator对象不会更改,您可以简单地保留返回的值,而不是每次都计算它。
IsMobile = function () {
var android = function() {
return navigator.userAgent.match(/Android/i);
},
blackBerry = function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS = function() {
return navigator.userAgent.match(/iPhone/i);
},
windows = function() {
return navigator.userAgent.match(/IEMobile/i);
},
anyMobile = function() {
if (android() || blackBerry() || iOS() || windows()) {
return true;
}
return false;
};
return anyMobile();
}();
console.log(IsMobile);
相关文章:
- 对于loop.if-仅在经过所有间隔后返回true
- 如果函数返回True,则显示Javascript按钮
- Javascript If else 只返回 TRUE 或只返回 FALSE
- 过滤器返回true或false
- 我对“;返回true"嵌套函数内部;t工作
- 如何在成功输入时使“返回TRUE”
- 检查一个元素是否有一个类与另一个类总是返回true
- JavaScript函数未返回true
- 如果URL中有任何字符串变体匹配,则返回true
- 如何使以下函数返回true或false
- 使用“in”关键字检查 0 始终返回 true
- hasOwnProperty 在对照父对象属性进行检查时返回 true
- 为什么 isNaN 总是返回 true
- _.数组中的每个查找值都返回 true 或 false.使用下划线 JS
- 错误地返回true
- 为什么asp:LinkButton服务器端事件没有'当clientClick返回true时,t激发
- 阻止表单提交 javascript 为什么有一个明显的错误语句返回 true
- Node js命令器args返回true而不是值
- 如何将html表单与php链接,以便在例如单击按钮时返回true
- 从OnClientClick调用函数时,在JavaScript中返回true