簡體   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