我正在尝试在 JavaScript 中创建一个对象,并且正在关注 Mozilla's tutorial 。该教程工作得很好,但是当我将该技术应用于我的代码时,它不起作用。 (我做错了什么,但我没有看到)。我对所有方法进行了编码,没有收到任何错误,我初始化了对象,也没有收到任何错误,我什至调用了我的方法,也没有收到错误,但返回值是一个带有我的字符串代码而不是我期望的值
function JavaScriptObj(id, datatype) {
function initialize(id, datatype) {
if (typeof id === 'number' && id > 1) {
this.theID = id;
} else {
console.error("ERROR: JavaScriptObj.initialize" + id + "is NOT a valid argument");
}
if (typeof datatype === 'string') {
this.data_type = datatype;
} else {
console.error("ERROR: JavaScriptObj.initialize" + datatype + "is NOT a valid argument");
}
}
}
JavaScriptObj.prototype.getSectionName = function(){
var SectionName = "section-" + this.theID;
return SectionName;
};
var person2 = new JavaScriptObj(2, "texteditor");
alert(person2.getSectionName);
这是我的jsfiddle
提前致谢! :-)
最佳答案
删除initialize
嵌套函数:
function JavaScriptObj(id, datatype) {
if (typeof id === 'number' && id > 1) {
this.theID = id;
} else {
console.error("ERROR: JavaScriptObj: " + id + "is NOT a valid argument");
}
if (typeof datatype === 'string') {
this.data_type = datatype;
} else {
console.error("ERROR: JavaScriptObj: " + datatype + "is NOT a valid argument");
}
}
JavaScriptObj.prototype.getSectionName = function(){
var SectionName = "section-" + this.theID;
return SectionName;
};
var person2 = new JavaScriptObj(2, "texteditor");
alert(person2.getSectionName()); // need to call it too
关于javascript - 如何在 Javascript 和 OOP 中创建方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19612770/