Example 1: javascript create class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
present = () => {
console.log(`Hi! i'm ${this.name} and i'm ${this.age} years old`)
}
}
let me = new Person("tsuy", 15);
me.present();
Example 2: javascript class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduction() {
return `My name is ${name} and I am ${age} years old!`;
}
}
let john = new Person("John Smith", 18);
console.log(john.introduction());
Example 3: javascript classes
class MyClass {
constructor(FirstProperty, SecondProperty, etcetera) {
this.firstProperty = FirstProperty;
this.secondProperty = SecondProperty;
}
method(Parameters) {
}
get getBothValues()
{
return [firstProperty, secondProperty];
}
}
Example 4: javascript class
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea();
}
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
console.log(square.area);
Example 5: get methods of class javascript
class Hi {
constructor() {
console.log("hi");
}
my_method(){}
static my_static_method() {}
}
function getMethods(cl) {
return Object.getOwnPropertyNames(cl.prototype)
}
console.log(getMethods(Hi))
Example 6: class methods parameters python
class Foo (object):
# ^class name #^ inherits from object
bar = "Bar" #Class attribute.
def __init__(self):
# #^ The first variable is the class instance in methods.
# # This is called "self" by convention, but could be any name you want.
#^ double underscore (dunder) methods are usually special. This one
# gets called immediately after a new instance is created.
self.variable = "Foo" #instance attribute.
print self.variable, self.bar #<---self.bar references class attribute
self.bar = " Bar is now Baz" #<---self.bar is now an instance attribute
print self.variable, self.bar
def method(self, arg1, arg2):
#This method has arguments. You would call it like this: instance.method(1, 2)
print "in method (args):", arg1, arg2
print "in method (attributes):", self.variable, self.bar
a = Foo() # this calls __init__ (indirectly), output:
# Foo bar
# Foo Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
# in method (args): 1 2
# in method (attributes): bar Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2). This makes it a little more explicit what the argument "self" actually is.
class Bar(object):
def __init__(self, arg):
self.arg = arg
self.Foo = Foo()
b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo