Search code examples
javascriptclassobjecttypeerrorgetter-setter

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:

<!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.