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 writing the setBSize method? How do I expose the public methods of b automatically? I want to do the call like this
a.setSize(5);
Also I need a reference to new B();
which is b inside A()
You could always set the prototype of A
to B
if you want to inherit all the methods in B
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);
In jQuery
: $.extend(that, new B());
In 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 private
variables in B()
class define them as var someVar
, and all public (overridable) variables as that.somePublicVar
You can use 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 invoke B
in context of A
, and what happens is that all own properties of the B
instance are going to be assigned to this
which is A
instance. This pattern is called constructor or methods borrowing.
You should utilize prototyping.
make a constructor which shares the function among all the classes(objects):
var myConstructor = function(newSize){
this.setSize = function(newSize)
{
...
}
}
Now you do instanciation:
var a = new myConstructor(someSize);
var b = new myConstrucotr(someSize);
Now with this change a.setSize()
is the same as b.setSize()
Using prototype for inheriting the method setSize
and discarding all the this
and that
code.
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
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.