How to expose public methods of member variables in JS

I have a class

function A()
{
   var that = this;
   var b = new B(); 
   this.setBSize = function(newSize)
   {
      b.setSize(newSize);
   }


};

function B()
{
   var that = this;

   this.setSize = function(newSize)
   {
   ...
   }
}

a = new A();
a.setBSize(5);

      

How do I avoid using the setBSize method? How can I publish public b methods automatically? I want to make a call like this

a.setSize(5);

      

Also I need a link to new B();

which is insideA()

+3


source to share


5 answers


You can always set prototype A

to B

if you want to inherit all methods inB

function A() {
    var that = this;
};

function B() {
    var that = this;

    this.setSize = function (newSize) {
        console.log(newSize); // 5
    }
}

A.prototype = new B();

a = new A();
a.setSize(5);

      



FIDDLE

+3


source


B jQuery

: $.extend(that, new B());

B angular

:angular.extend(that, new B());

function A()
{
   var that = this;
   $.extend(that, new B());
};

function B()
{
   var that = this;

   this.setSize = function(newSize)
   {
   ...
   }
}

a = new A();
a.setSize(5);

      



And if you want to use any variables private

in the class B()

, define them as var someVar

and all public (overridden) variables asthat.somePublicVar

+2


source


You can use a call

method for this:

function A() {
    var that = this;
    B.call(this);
};

function B() {
    var that = this;
    this.setSize = function (newSize) {
        this.size = newSize;
    }
}

var a = new A();
a.setSize(5);

      

Basically you are calling B

in context A

and what happens is that all of the instance's own properties B

will be assigned this

, which is the instance A

. This pattern is called constructor or borrowing method.

+1


source


You have to use prototyping.

create a constructor that shares the function among all classes (objects):

var myConstructor = function(newSize){

   this.setSize = function(newSize)
   {
   ...
   }
}

      

Now you do the initialization:

var a = new myConstructor(someSize);

var b = new myConstrucotr(someSize);

      

Now this change is the a.setSize()

same asb.setSize()

+1


source


Using prototype to inherit a method setSize

and discard all code this

and that

.

function B() {
};
function A() {
    B.call(this);
};

B.prototype.setSize = function(newSize) {
    console.log(newSize);
}

A.prototype = Object.create(B.prototype);
A.prototype.constructor = A;
var a = new A();
a.setSize(5);               // 5
console.log(a instanceof A);// true
console.log(a instanceof B);// true

      

+1


source







All Articles