繁体   English   中英

javascript 'use strict' 和 Object.defineProperty 设置器

[英]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);

当我尝试在严格模式下运行此代码时,我总是收到此错误ReferenceError: assignment to undeclared variable temperature我想了解哪种方法是解决此问题的最佳方法

当您使用“使用严格”时,您不能使用未声明的变量。 在“this.name = name;”之后输入“var 温度;”

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM