Uncaught TypeError: Cannot read property ‘xxxxx‘ of undefined

Uncaught TypeError: Cannot read property ‘xxxxx’ of undefined

Reason for error: The xxxx attribute is obtained from an undefined object

Error code example: Uncaught TypeError: Cannot read property 'offsetLeft' of undefined The problem here is that the "this.head" of the snake class is undefined

var Snake = (function () {
    
    
    function Snake() {
    
    
        window.onload = function () {
    
     
            this.bodies = document.getElementById('snake').getElementsByTagName('div');
        }.bind(this);
    }
    Object.defineProperty(Snake.prototype, "X", {
    
    
        // 获取蛇头坐标
        get: function () {
    
    
            return this.head.offsetLeft;
        },
        // 设置蛇头的坐标
        set: function (value) {
    
    
            this.head.style.left = value + 'px';
        },
        enumerable: false,
        configurable: true
    });
})();

Solution: Check if head is defined before getting offsetLeft

code show as below

var Snake = (function () {
    
    
    function Snake() {
    
    
        var that = this; // save the reference to `this` since it will change inside the onload function
        window.onload = function () {
    
     
            that.element = document.getElementById('snake');
            // 只会获取第一个 div
            that.head = document.querySelector('#snake > div');
            that.bodies = document.getElementById('snake').getElementsByTagName('div');
        };
    }
    Object.defineProperty(Snake.prototype, "X", {
    
    
        get: function () {
    
    
            return this.head ? this.head.offsetLeft : null; // check if the head exists before accessing it
        },
        set: function (value) {
    
    
            if (this.head) {
    
     // check if the head exists before setting its style
                this.head.style.left = value + 'px';
            }
        },
        enumerable: false,
        configurable: true
    });
})();

In fact, the

get: function () {
    
    
        // return this.head.offsetLeft; 将这个改为下面(加一个判断)
        return this.head ? this.head.offsetLeft : null;
     },
// 设置蛇头的坐标
set: function (value) {
    
    
        // this.head.style.left = value + 'px'; 这个也是加判断
        if (this.head) {
    
    
                this.head.style.left = value + 'px';
        }
}

(❤ ω ❤) Hope it helps you :)

Guess you like

Origin blog.csdn.net/weixin_72616433/article/details/130136079