简体   繁体   中英

Return value from nested private function

The following code works well in most cases except when I'm trying to return a value from the private function. How can I get the return value from private without exposing the private function ?

var _private = function() {    
  return 'hello' ;    
},
public = function() {
  _private();
};

Use this

var _private = function() {    
  return 'hello' ;    
},
public = function() {
  return _private();
};

You have to add the return statement return _private()

 var _private = function() { return 'hello' ; }, public = function() { return _private(); }; console.log(public()); console.log(_private()); 

NOTE: your private function is not very private. As you can see in the above snippet. The function is accessible

Javascript has no private functions natively, You will need to use a closure to create a privately accessible scope for you _private function. Here is a quick example.

 var public = (function(){ var _private = function() { return 'hello' ; } return function() { return _private(); } })() console.log( public(), typeof _private === 'undefined' ) 

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