javascript 'используйте строгий' и и Object.defineProperty setter - PullRequest
1 голос
/ 18 апреля 2020
'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);

Когда я пытаюсь запустить этот код в строгом режиме, я всегда получаю эту ошибку ReferenceError: присвоение необъявленной переменной температуры Я хотел бы понять, каков наилучший способ обойти эту проблему

1 Ответ

1 голос
/ 18 апреля 2020

Когда вы используете «строгий», вы не можете использовать необъявленную переменную. После "this.name = name;" поставить "вар температура";

'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);
...