Skip to content

Using prototype based class

Wang Renxin edited this page May 31, 2022 · 3 revisions

MY-BASIC supports prototype-based programming paradigm which is a kind of OOP (Object-Oriented Programming). When we mention "class instance" or "prototype" in MY-BASIC, we mean the same thing. This programming paradigm can also be known as prototypal, prototype-oriented, classless, or instance-based programming. Use a pair of CLASS/ENDCLASS statements to define a class (a prototype object). Use VAR to declare a member variable in a class. It's possible to define member function (aka. method) in a prototype with the DEF/ENDDEF statements as well. Write another prototype surrounding with a pair of parentheses after a declaration statement to inherit from it (use it as a meta class). Use NEW to copy a new clone of a prototype.

See following for example to use a prototype in MY-BASIC:

class foo
	var a = 1
	def fun(b)
		return a + b
	enddef
endclass

class bar(foo)  ' Use foo as a meta class (inheriting)
	var a = 2
endclass

inst = new(bar) ' Create a new clone of bar
print inst.fun(3);

bar will simply link foo as a meta class. But inst will create a new clone of bar and keep the meta link from foo.

The GET statement can be also applied to a class instance to get a member of it. It results the value of a field variable or the routine object of a sub routine:

print get(foo, "A");   ' Result the value of "A"
print get(foo, "FUN"); ' Result the routine object

The SET statement can be applied to a class instance to set the value of a member variable:

set(foo, "A", 42)
print get(foo, "A"); ' Result 42
Clone this wiki locally