How to use the private constructor method in an instance of an object

I created a constructor function. Now I am adding properties and methods to it. Now I also add the private function ceta () to it. After that I create an instance (obj1) from the constructor function, how can I use a private function to instantiate an object (not using a call, apply, bind).

<html>
<head></head>
<body>

<script>

function alpha(){
  this.a = 10;
  this.b = 20;
  this.beta = function(){
    this.c = 30; 
    alert (c);
  }
  var ceta = function(){
    alert ("hi!");
  }
}

var obj1 = new alpha;

obj1.beta();// this works
obj1.ceta();// this not 

</script>

</body>
</html>
Run codeHide result
+4
source share
1 answer

cetais in the scope of the constructor function alpha, but does not belong to the objects that are being built. It can be used or closed and returned from the function this.beta. For instance:

function alpha(){
  this.a = 10;
  this.b = 20;
  this.beta = function(){
    ceta(); // <<-- invoke here for some purpose
    this.c = 30; 
    alert(this.c);
    return ceta; // <<-- or return here
  }
  var ceta = function(){
    alert ("hi!");
  }
}

var obj  = new alpha(),
    ceta = obj.beta(); // alerts twice and obj.c is set to 30

. ceta , .

ceta alpha, alpha.

+1

Source: https://habr.com/ru/post/1696300/


All Articles