簡體   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