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()
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
source to share
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.
source to share
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()
source to share
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
source to share