[英]Why won't this object method return a boolean value Javascript
My app's js file includes this bit here: 我的应用程序的js文件在此处包含以下内容:
var drawer = document.getElementById('b_001');
drawer.isOpen = function() {
this.classList.contains('open');
};
When I call it in the console, drawer.isOpen()
, I expect a boolean value, true
or false
. 在控制台drawer.isOpen()
调用它时,我期望一个布尔值true
或false
。 However, undefined
is returned instead. 但是,将返回undefined
。 Why is this? 为什么是这样?
你需要一个退货声明
return this.classList.contains('open');
You'll have to return it: 您必须将其退回 :
drawer.isOpen = function() {
return this.classList.contains('open');
//^ here
};
If a function doesn't return anything, the return value is considered undefined
, as this snippet demonstrates: 如果某个函数不返回任何内容,则该返回值被视为undefined
,如以下代码片段所示:
var report = document.querySelector('#result'); report.innerHTML += doStuff(5); // nothing returned report.innerHTML += '<br>'+addFive(5); // a result is returned function doStuff(val) { val = val || 0; val += 5; } function addFive(val) { val = val || 0; val += 5; return val; }
<div id="result"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.