works:programmer:js:class-example

Пример создания класса на JS

Чуть новее чем в class

Как классы на JS создаю Я. Небольшой и понятный код как легко создать класс который будет работать на всех более или менее новых браузерах.

function MyBaseClass() {
	return {
			'toString': function() { return "x=" + this.x + " y=" + this.y;  }
	};
}
 
function MyClass(arg_x, arg_y) {
	if ( ! (this instanceof MyClass)) return new MyClass(arg_x, arg_y);
 
	// Public scope variables
	var _exports_ = new MyBaseClass();
	_exports_['x'] = arg_x;
	_exports_['y'] = arg_y;
 
	// Private scope variables
	var x = arg_x, y  = arg_y;
 
	_exports_['getLocalX'] = function() { return x; };
	_exports_['setLocalX'] = function(value) { x = value; };
	_exports_['getLocalY'] = function() { return y; };
	_exports_['setLocalY'] = function(value) { y = value; };
 
	_exports_['getPublicX'] = function() { return this.x; };
	_exports_['setPublicX'] = function(value) { this.x = value; };
	_exports_['getPublicY'] = function() { return this.y; };
	_exports_['setPublicY'] = function(value) { this.y = value; };
 
	return _exports_;
}
 
// Example of usage
var a = new MyClass(0, 0); // With new keyword
a.setLocalX(5);
a.setPublicX(10);
var b = MyClass(100, 100); // Without new keyword
b.setLocalX(105);
b.setPublicX(110);
 
console.log(a, ""+a, a.getLocalX());
console.log(b, ""+b, b.getLocalX());

Старый JS в виде prototypes работает для NodeJS версий 0.12

function extend (base, constructor) {
	var prototype = new Function();
	prototype.prototype = base.prototype;
	constructor.prototype = new prototype();
	constructor.prototype.constructor = constructor;
}
 
// Base class
function App(name, surname) {
	if (!(this instanceof App)) throw new Error("not constructed");
	this._name = name;
	this._surname = surname;
}
 
App.prototype.getName = function() {
	return this._name;
}
 
App.prototype.toString = function() {
	const about = {};
	about[this.__proto__.constructor.name] = {
		"name": this._name,
		"surname": this._surname
	}
	return JSON.stringify(about);
}
 
// Extended Class
function Zeffa(name, surname, age) {
	App.call(this, name, surname);
	this._age = age;
}
 
// important that this happens before you override methods on parent class
extend(App, Zeffa);
 
Zeffa.prototype.getAge = function() {
	return this._age;
}
 
// Test
const a = new Zeffa("Василий", "Пупкин", 18);
console.log("" + a);
console.log(a.getAge());
works/programmer/js/class-example.txt · Last modified: 2022/04/07 07:20 by Chugreev Eugene