简体   繁体   中英

Javascript: How to call a method from a constructor? My variable returns Undefined

I am creating a javascript class to handle SVG tags in HTML. (I know that there are plenty of classes that does this already but I did not succeed with transformations via svg.js. Also, I have made all the required functions to work and I just want to implement them as a class for syntactical ease.)

However, not being that familiar with javascript, I have trouble with a variable that is set to Undefined in my constructor:

class SLD {
    constructor(container,x=1000, y=1000) {
        this.ctn = document.getElementById(container);
        this.svgobj = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        // Defining object attributes  
        var obj = {
            'width': "1000",
            'height': "1000",
            'xmlns':"http://www.w3.org/2000/svg", 
            'version':"1.1",
            'xmlns:xlink':"http://www.w3.org/1999/xlink"
        };
        // Setting attribute via for loop
        for(prop in obj) {
            this.svgobj.setAttribute(prop, obj[prop])  
        }
    }

While trying to run it, I am returned the following error code: 在此处输入图像描述

How do I define the variable properly? I am using Chrome (version 83.0.4103.116) and the browser supports classes as far as I am noticed.

Let me know if I should provide any other relevant information.

I assume prop hasn't been declared yet so you'll need to use var.

for(var prop in obj) {
    this.svgobj.setAttribute(prop, obj[prop])  
}

You could try this:

for (const prop in obj) {
  this.svgobj.setAttribute(prop, obj[prop]);
}

Variable declaration was your problem.

Your code could be optimized by replacing the for loop with:

Object.entries({
    'width': "20",
    'height': "20",
    'xmlns':"http://www.w3.org/2000/svg", 
    'version':"1.1",
    'xmlns:xlink':"http://www.w3.org/1999/xlink"
}).forEach(([prop,value])=>svgobj.setAttribute(prop, value));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM