newguy newguy - 5 months ago 9
Javascript Question

Having problems with init function in javascript and using the properties after assigning in init function

I am writing three classes and want to display something, the last class uses an init function to assign values to its properties, see below. But it doesn't work as I expected.

class Circle1 {
constructor(options) {

}

render() {
document.getElementById('result').innerHTML = 'Hello, ';
}
}

class Circle2 {
constructor(options) {

}

render() {
document.getElementById('result').innerHTML += 'My';
}
}

class Circle {
constuctor(options) {
this.x = options.x;
this.y = options.y;
this.length = options.length;

this.bodies = [];
this.init(options);
}

init(options) {
this.first = new Circle1(options);
for (let i = 0; i < this.length; i++) {
this.bodies.push(new Circle2(options));
}
}

render() {
/**
this.first.render();

this.bodies.forEach(function(body) {
body.render();
});
**/
document.getElementById('result').innerHTML += 'World';

}
}

var c = new Circle({
x: 20,
y: 20,
length: 6
});

c.render();


This code will display "World" to the screen.

However, if I uncomment the commented code, and try to display "Hello, My (times length) World" to the screen but it doesn't show anything.

I am very confused with the init function in the class. I thought I can assign values to the properties in that function but the result tells me it doesn't work. What is wrong with my code?

Here is the jsfiddle link.

Answer

You have an error in the name of the constructor (constructor is not called):

class Circle {
    constuctor(options) {

==>

class Circle {
    constructor(options) {

[ https://jsfiddle.net/5sv5hwLb/ ]

Comments