First of all, I'm quite new to both OOP and NodeJS. My only experience with classes so far, are in PHP.
I'm trying to make a javascript class called Clients, using the defineClass module in NPM. Then I want to add sub-classes to it, with even more functionality. The reason I want some of the functionality in sub-classes, is because some of them might have quite alot of functionality.
Here is my code:
var defineClass = require("defineClass").defineClass
var Client = defineClass({
scpConnected: false,
constructor: function (socketId) {
this.id = socketId;
},
test: function (test){
console.log('Test!!! '+ test);
}
});
var SSH = defineClass({
_super: Client,
connected: false,
busy: false,
buffer: '',
constructor: function () {
queue = [];
},
ssh: {
connect: function (IP) {
console.log('Connecting to '+ IP +'...');
}
}
});
var client = new Client('Test');
client.ssh.connect();
It seems like "client" doesn't get the SSH abilities as I was expecting.
What am I doing wrong here? :)
New Code
var defineClass = require("defineClass").defineClass
var Client = defineClass({
scpConnected: false,
constructor: function (socketId) {
this.id = socketId;
},
test: function (test){
console.log('Test!!! '+ test);
},
SSH: defineClass({
connected: false,
busy: false,
buffer: '',
constructor: function () {
queue = [];
},
connect: function (IP) {
console.log('Connecting to '+ IP +'...');
}
})
});
var client = new Client('Test');
client.SSH.connect('test');
As I can see in your sample, you are actually creating instance of Client instead of SSH:
var client = new Client('Test');
client.ssh.connect();
You should write:
var client = new SSH('Test');
client.ssh.connect();
Note that parent class doesn't have the functionality of its children, it's against the idea of inheritance.
There are clearly some problems with inheritance.
Consider the following example (corresponding to your code) in PHP:
<?php
class Client {
public function __construct($socketId) {
$this->id = $socketId;
}
}
class SSH extends Client {
public function __construct() {
$this->queue = new Array();
}
public $ssh = "whatever";
}
$client = new Client('Test');
//What is the $client->ssh now?
?>