То, что большинство людей делает, это использует функции конструктора, например:
function MyClass(a, b) {
// Private instance properties
var x = "secret";
var y = "also secret";
// Public instance properties
this.a = a;
this.b = b;
// "Privileged" methods; can access private and public properties
this.foo = function () {
return x + " " + this.a;
};
}
// "Public" methods; cannot access private properties
MyClass.prototype.bar = function () {
return this.a + " " + this.b;
};
// Public shared properties; not recommended:
MyClass.prototype.w = "stuff";
// Static methods
MyClass.baz = function () {
return "i am useless";
};
Затем вы использовали бы эту функцию конструктора следующим образом:
var instance = new MyClass("hi", "Meen");
asssert.equal(instance.foo(), "secret hi");
assert.equal(instance.bar(), "hi Meen");
assert.equal(MyClass.baz(), "i am useless");
var also = new MyClass("hi", "Raynos");
instance.w = "more stuff";
assert.equal(also.w, "more stuff");
Есливы хотели бы наследовать, вы бы сделали что-то вроде:
function Inherited(a) {
// apply parent constructor function
MyClass.call(this, a, "Domenic");
}
Inherited.prototype = Object.create(MyClass.prototype);
var inherited = new Inherited("hello there good chap");
assert.equal(inherited.a, "hello there good chap");
assert.equal(inherited.foo(), "secret hello there good chap");
assert.equal(inherited.bar(), "hello there good chap Domenic");