简体   繁体   中英

Why won't this object method return a boolean value Javascript

My app's js file includes this bit here:

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 . However, undefined is returned instead. 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:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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