繁体   English   中英

JavaScript返回函数不值

[英]JavaScript returns function not value

我有一个从中调用函数的对象。 它返回值而不是值本身。 这可能是重复的,但我找不到合适的解决方案。 因此,对此问题的任何流行词汇都将受到高度赞赏。

 var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0]; var asd = { getWindowWidth: function() { var x = w.innerWidth || e.clientWidth || g.clientWidth; return x; }, getWindowHeight: function() { var x = (function() { return w.innerWidth || e.clientWidth || g.clientWidth; })(); return x; }, init: function() { console.log("init fired"); console.log(this.getWindowWidth); console.log(this.getWindowHeight); console.log(typeof(this.getWindowHeight)); } } asd.init(); 

预先感谢您对我们的支持。

使用括号来调用该函数,否则您仅捕获了函数本身。

console.log(this.getWindowWidth());
//                             ^^

只需像这样更改您的函数this.getWindowWidth()

如果没有paranthesis ,它将执行实际的函数调用,并且不会返回值。

 var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0]; var asd = { getWindowWidth: function() { var x = w.innerWidth || e.clientWidth || g.clientWidth; return x; }, getWindowHeight: function() { var x = (function() { return w.innerWidth || e.clientWidth || g.clientWidth; })(); return x; }, init: function() { console.log("init fired"); console.log(this.getWindowWidth()); console.log(this.getWindowHeight()); console.log(typeof(this.getWindowHeight())); } } asd.init(); 

您正在使用this.getWindowHeight而不是this.getWindowHeight()

 var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0]; var asd = { getWindowWidth: function() { var x = w.innerWidth || e.clientWidth || g.clientWidth; return x; }, getWindowHeight: function() { var x = (function() { return w.innerWidth || e.clientWidth || g.clientWidth; })(); return x; }, init: function() { console.log("init fired"); console.log(this.getWindowWidth()); console.log(this.getWindowHeight()); console.log(typeof(this.getWindowHeight())); } } asd.init(); 

调用了init函数,但其​​他函数没有那么多。 正如Alex K.所说,您需要改变

console.log(this.getWindowWidth);
console.log(this.getWindowHeight);
console.log(typeof(this.getWindowHeight));

至:

console.log(this.getWindowWidth());
console.log(this.getWindowHeight());
console.log(typeof(this.getWindowHeight()));

 var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0]; var asd = { getWindowWidth: function() { var x = w.innerWidth || e.clientWidth || g.clientWidth; return x; }, getWindowHeight: function() { var x = (function() { return w.innerWidth || e.clientWidth || g.clientWidth; })(); return x; }, init: function() { console.log("init fired"); console.log(this.getWindowWidth()); console.log(this.getWindowHeight()); console.log(typeof(this.getWindowHeight())); } } asd.init(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM