Error when using other properties in this during object initialization

Asked 2 months ago, Updated 2 months ago, 3 views

I am currently using javascript and HTML to create certain functions, but there was an error in the definition of the object during the production process, so I cannot get out of it.Please tell me how to solve this.

Error Contents

test.html:23 Uncaught TypeError: Cannot read properties of undefined (reading 'options')
    at test.html:23:26

source code:

<body>
    
    <pid="display"></p>
        <select id="number">
            <option value="1">10</option>
            <option value="2">20</option>
            <option value="3">30</option>
            <button id="output">output</button>
    </select>
        
    <script>
    
    variable = {
        select: document.getElementById('number'),
        index —This.select.options.selectedIndex,
        selected: this.select.options [this.index],
        display: document.getElementById('display'),
        button: document.getElementById('output'),
        output:this.button.addEventLister('click',()=>{
           element.display.innerText=element.selected.value
        }),
    }
    
    </script>

</body>

javascript html dom

2022-09-30 13:56

2 Answers

There is a problem mainly with using this.

  • The this outside the function (function) is a global object and does not point to the intended object
  • The value of the part that uses this in the first place may vary from initialization depending on the user's choice, so you must ask for it every time you are called
  • So, function (method) will solve this problem

Below are some helpful codes and links, but basically it is recommended that you understand them systematically in books.

this references

this references vary by context.

However, although it may vary, it does not have the functionality that the questioner expected.

The code in question expects this to be used in the object initializer (literal) to point to the object itself being initialized, but JavaScript does not have such a feature. I don't think this has any other syntax to do so.

The expression this can refer to the object being initialized is sometimes used primarily for functions (constructors) called by new.

In , what the question code this refers to is the global object (same as window for browsers).Please check the code below.

vara="Value of global variable a"

letobj = {
    a: "Obj property a value",
    what_is_this —this.a,
}

// where obj.what_is_this is the same value as the global variable a.
// In other words, it is the value of the global variable a.
// It is not "value of property a of obj".
console.log("obj.what_is_this value is:",obj.what_is_this)

// The above shows that this here points to a global object.
// Of course, it is the same even outside the object initializer.
// Therefore, the following values are the same.
console.log("This.a value is:", this.a)

Methods Example

Leave as much of the code form of the question as possible:

 variable={
    select: document.getElementById('number'),
    getIndex: function(){
        return this.select.options.selectedIndex
    },
    getSelected: function(){
        return this.select.options [this.getIndex()]
    },
    display: document.getElementById('display'),
    button: document.getElementById('output'),
    init:function(){
        This.button.addEventListener('click',()=>{
            this.display.innerText=this.getSelected().value
        })
    },
}
element.init()

More idiomatic JavaScript (object orientation using constructor functions and prototype):

functionApp(){
    this.select= document.getElementById('number'),
    this.display= document.getElementById('display'),
    this.button= document.getElementById('output'),
    This.button.addEventListener('click',()=>{
        this.display.innerText=this.getSelected().value
    })
}
App.prototype.getIndex=function(){
    return this.select.options.selectedIndex
}
App.prototype.getSelected=function(){
    return this.select.options [this.getIndex()]
}

var app = new App()

Using the most recent syntax:

class App {
    select = document.getElementById('number')
    display = document.getElementById('display')
    button= document.getElementById('output')

    constructor(){
        This.button.addEventListener('click',()=>{
            this.display.innerText=this.getSelected().value
        })
    }
    getIndex(){
        return this.select.options.selectedIndex
    }
    getSelected(){
        return this.select.options [this.getIndex()]
    }
}

let app = new App()


2022-09-30 13:56

There is a problem with how to initialize variables.References to this in creating values for initialization of the variable element are not what you expect.Therefore, this.select becomes undefined and references this.select.options to undefined.options leading to this error: "Properties cannot be viewed."

Also, it is not necessary to combine the variables used this time as element properties at this time.You can initialize each variable in order as follows:

const select= document.getElementById('number');
const index = this.select.options.selectedIndex;
const selected = this.select.options [this.index];
// (omitted hereinafter)

Furthermore, for this process, the value of the option selected in select should be obtained at the time of execution of the option selected in select.This is because even if the selected option changes, the above substitution will not be re-executed and the value will not be updated.

If you think about that, you can see that there is no need to use variables in this process.For example:

 document.getElementById('output').addEventListener('click',()=>{
  document.getElementById('display').innerText= document.getElementById('number').value;
});
<body>
    <pid="display"></p>
    <select id="number">
        <option value="1">10</option>
        <option value="2">20</option>
        <option value="3">30</option>
    </select>
    <button id="output">output</button>
</body>


2022-09-30 13:56

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.