Uncaught TypeError: Cannot read property 'prototype' of undefined 是在JaveScript 中在获取一个未定义对象的原型属性中常出现的一个错误,它可能由尝试去获取未定义的类或函数引起。
错误代码示例:
var Snake = (function () {
window.onload = function Snake() {
this.element = document.getElementById('snake');
// 只会获取第一个 div
this.head = document.querySelector('#snake > div');
this.bodies = document.getElementById('snake').getElementsByTagName('div');
}
Object.defineProperty(Snake.prototype, "X", {
// 获取坐标
get: function () {
return this.head.offsetLeft;
},
// 设置蛇头的坐标
set: function (value) {
this.head.style.left = value + 'px';
},
enumerable: false,
configurable: true
});
}());
Snake 类函数并没有正确定义,widow.onload 函数在这个类中不应该用为构造函数,去除掉它的函数名并将它作为一个常规函数
修改后:
var Snake = (function () {
function Snake() {
window.onload = function () {
this.element = document.getElementById('snake');
// 只会获取第一个 div
this.head = document.querySelector('#snake > div');
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
});
})();