我有一个模块。我正在做的是当我创建一个对象func
的新实例时,模块内部的函数会自动在构造函数中被调用。如果b为真,则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
答案 0 :(得分:0)
因为这个 -
return {
func: func
}
要公开访问的任何移动设备都是object
,其中包含一个功能。
如果你要改为func: func()
(现在这将是一个函数调用,它将返回一个布尔值),它应该可以工作!
查看精美解释的概念here
答案 1 :(得分:0)
示例中的第一行是声明一个充当构造函数的函数。
var IsMobile = function () { this.anyMobile() };
当你致电新的IsMobile()
时在您的情况下,在构造函数代码中调用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());
此外,由于导航器对象没有改变,您只需保留返回的值,而不是每次都计算它。
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);