Home > OS >  Type Error: How do I get a method to execute like a function in Javascript?
Type Error: How do I get a method to execute like a function in Javascript?

Time:05-14

I was trying to create a Javascript function in HTML,which should create a rectangle and set the size to the likings of the user with this code:

class Rectangle{
  constructor(height, width){
    this.height = height;
    this.width = width;

  function createRectangle(Rectangle){
    var input1 = document.getElementbyId("1stinput").value;
    var input2 = document.getElementbyId("#2ndinput").value;
    var input1int = parseFloat(input1);
    var input2int = parseFloat(input2);
    var Rectangle1 = new Rectangle(this.height=input1int, this.width=input2int);};
    document.querySelector("Rectangle").setAttribute('width', parseFloat(Rectangle1.width));
    document.querySelector("Rectangle").setAttribute('height', parseFloat(Rectangle1.height));
};
};
</script>
<input type="text" name="" value="" id="1stinput">
<input type="text" name="" value="" id="2ndinput">
<button onclick=Rectangle.createRectangle(Rectangle)>create</button>
<svg width=0 height=0>
  <rect width=0 height=0 style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" id="Rectangle"/>
</svg>

But that didn't work,I got this Error:

Uncaught TypeError: Rectangle.createRectangle is not a function
    at HTMLButtonElement.onclick

So I think,that createRectangle shoud be a method,but I don't know how to implement methods in the button,can someone Please help me? That would be very nice,thank you!!!

CodePudding user response:

You may want to revisit how you're approaching this. Classes have methods so you can't just add a function to them (here's the documentation). Additionally, maybe keep DOM manipulations out the class itself, and just let that return an HTML string based on the input values. You can then add that to a DOM element of your choosing.

class Rectangle {
  
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  createRectangle() {
    return `
      <svg>
        <rect width="${this.width}px" height="${this.height}px"></rect>
      </svg>
    `;
  }

}

const input1 = document.querySelector('#input1');
const input2 = document.querySelector('#input2');
const button = document.querySelector('button');
const output = document.querySelector('#output');

button.addEventListener('click', handleClick, false);

function handleClick() {
  const n1 = parseFloat(input1.value);
  const n2 = parseFloat(input2.value);
  const rectangle = new Rectangle(n1, n2);
  output.innerHTML = rectangle.createRectangle();
}
svg { width: 100%; }
rect { fill: rgb(0, 0, 255); stroke-width: 3; stroke: rgb(0, 0, 0);}
#output { margin-top: 1em; }
<input type="text" id="input1">
<input type="text" id="input2">
<button>create</button>
<div id="output"></div>

Additional documentation

  • Related