Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Uncaught TypeError on methods when using Setters and Getters in Javascript Class

I’m trying to use setters and getters in my class to set the url field as an object with its own properties (value, domain, icon), but when I use a string method like "startsWith()" on the url parameter, I am getting the error "Uncaught TypeError: url.startsWith is not a function."

I read about setters and getters before trying to do this and understood that to avoid problems with the setter and getter name over the property name, I just have to use the property with a "_" at the beginning of the property name inside the Setter or Getter.

Simple HTML for this example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body style="background-color: #333;">   
    

    <script src="./main.js" type="module"></script>
</body>
</html>

JS

class Url{
    constructor(url){
        this.url = {
            value : url,
            domain : url.startsWith('https://') ? url.split(8) : url.split(7),
            icon : url + 'favicon.ico'
        }
    }

    get url(){
        return this._url
    }

    set url(url){
        this._url = {
            value : url,
            domain : url.startsWith('https://') ? url.split(8) : url.split(7),
            icon : url + 'favicon.ico'
        }
    }
}

const test = new Url("https://youtube.com")

console.log(test.url.domain)

>Solution :

When you pass the URL string into your constructor function, it builds an object and assigns it to this.url. That will cause your setter function to be called. However, the setter also expects a plain string, so you get that exception.

From the constructor, all you really need is

this.url = url;

to pass the string parameter to the setter.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading