isolated-sandbox / examples /javascript_objects.js
ChefAdorous's picture
Deploy Code Execution Sandbox with FastAPI and Docker
a89f25d
// JavaScript Example: Objects and Classes
class Calculator {
constructor() {
this.history = [];
}
add(a, b) {
const result = a + b;
this.history.push(`${a} + ${b} = ${result}`);
return result;
}
multiply(a, b) {
const result = a * b;
this.history.push(`${a} * ${b} = ${result}`);
return result;
}
showHistory() {
console.log('Calculation History:');
this.history.forEach(entry => console.log(entry));
}
}
// Create calculator instance
const calc = new Calculator();
// Perform calculations
console.log('10 + 5 =', calc.add(10, 5));
console.log('10 * 5 =', calc.multiply(10, 5));
console.log('7 * 8 =', calc.multiply(7, 8));
// Show history
calc.showHistory();
// Object with methods
const person = {
name: 'Alice',
age: 30,
greet() {
return `Hello, I'm ${this.name} and I'm ${this.age} years old.`;
},
haveBirthday() {
this.age++;
}
};
console.log(person.greet());
person.haveBirthday();
console.log(person.greet());