Uncaught TypeError: Cannot read property ‘xxxxx‘ of undefined

Uncaught TypeError: Cannot read property ‘xxxxx’ of undefined

报错原因:xxxx属性是从一个未定义的对象身上获取

错误代码示例:Uncaught TypeError: Cannot read property ‘offsetLeft’ of undefined这里的问题就是蛇类的 “this.head” 未定义

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
    });
})();

解决方案:检查在获取 offsetLeft 之前,head 是否被定义了

代码如下

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
    });
})();

其实就是将

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

(❤ ω ❤) 希望对你有所帮助 :)

你可能感兴趣的:(javascript,前端,开发语言,其他)