尝试学习Js并无法理解DOM元素为何不获取值:
var Car = function(loc) {
var obj = Object.create(Car.prototype);
obj.loc = loc;
obj.move = move;
return obj;
};
Car.prototype = {
move : function() {
this.loc++;
}
};
var emy = Car(1);
emy.move();
document.getElementById("id").innerHTML = emy.loc;
因此,我创建了一个类构造函数及其原型对象,但是最后一行-
document.getElementById("id").innerHTML = emy.loc;
未被执行(除非我将其放在文件顶部)。这是为什么?片段:
https://jsfiddle.net/awj6mf1b/
最佳答案
您尚未定义移动方式:
var Car = function(loc) {
var obj = Object.create(Car.prototype);
obj.loc = loc;
obj.move = move; // <<< Here
return obj;
};
给出错误:
Uncaught ReferenceError: move is not defined
at Car (VM52:51)
at window.onload (VM52:61)
您可以通过在实例化过程中将函数放在对象中来解决此问题:
var Car = function(loc) {
var obj = Object.create(Car.prototype);
obj.loc = loc;
obj.move = function() {
this.loc++;
}
return obj;
};
或通过将函数正确添加到原型中:
var Car = function(loc) {
var obj = Object.create(Car.prototype);
obj.loc = loc;
// Removed move from here
return obj;
};
// This adds move to the cars prototype
Car.prototype.move = function() {
this.loc++;
}