简体   繁体   中英

how to create methods in Javascript and OOP

I'm trying to create an object in JavaScript and I'm following Mozilla's tutorial . the tutorial works just fine, but when I apply that technique to my code it doesn't work. (I'm doing something wrong but I don't see it). I coded all my methods and I don't get any errors, I initialize my object and I don't get any errors either, I even call my methods and I don't get errors, but the return value is a string with my code instead of the value that I'm expecting

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

this is my jsfiddle

thanks in advance! :-)

Remove the initialize nested function:

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

It looks like you're not actually executing/calling your method. In order to call your method, you need to put append parenthesis to the call:

alert(person2.getSectionName());

Just as an aside -- using console.log() instead of alert() tends to save you a few keystrokes and makes development a bit faster. Also, alert() is a blocking call that stops all other code execution on the page. While that won't make a difference when you're first starting out, it could potentially be a pain point down the road as your javascript ninja skills increase. Better to start the good habits sooner than later :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM