简体   繁体   中英

javascript 'use strict' and and Object.defineProperty setter

'use strict';

class DataClass{

        constructor(name){
            this.name = name;

            Object.defineProperties(this, {
                _archives :{
                    value : []

                },
                temperature : {

                    enumerable : true,
                    set : function(value){

                        // error message : InternalError: too much recursion
                        //this.temperature = value;
                        //error message  in case of 'use strict' : ReferenceError: assignment to undeclared variable temperature
                        temperature = value;
                        this._archives.push(value);

                    },
                    get : function(){
                        return ' yyy ';
                    } 
                },

            });
        }



 }



 var dataClass1 = new DataClass('giovanni');
 dataClass1.temperature = 45;
 console.log(dataClass1.temperature);

When i try to run this code in strict mode i get always this error ReferenceError: assignment to undeclared variable temperature i would like to understand which is the best way to work around this problem

When you use 'use strict' you cannot use an undeclared variable. After "this.name = name;"put "var temperature;"

'use strict';

class DataClass{

        constructor(name){
            this.name = name;
            var temperature; // <- private variable, completely different from the public one.
            Object.defineProperties(this, {
                _archives :{
                    value : []

                },
                temperature : { // <- public variable Object.temperature, internally this.temperature

                    enumerable : true,
                    set : function(value){

                        // error message : InternalError: too much recursion
                        //this.temperature = value; <-- Call the set again, that's why the loop.
                        //error message  in case of 'use strict' : ReferenceError: assignment to undeclared variable temperature
                        temperature = value;
                        this._archives.push(value);

                    },
                    get : function(){
                        return ' yyy ';
                    } 
                },

            });
        }



 }



 var dataClass1 = new DataClass('giovanni');
 dataClass1.temperature = 45;
 console.log(dataClass1.temperature);

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