简体   繁体   中英

JavaScript function giving an error saying

I am defining this function in JavaScript and I am getting an error like 'myobj is undefined' in firefox and chrome. How do I define a function argument? Where did i go wrong ? I am not even calling it and I wonder why i am getting an error. JsLint is not showing any error.

function makeBox (myobj) {
    if( myobj.fullname.length > 18 ) {
        myobj.fullname = myobj.fullname.slice(0 ,15 );
        myobj.fullname = myobj.fullname + '...';
    }
    var box = templates.box.supplant(myobj);
    return box;
}

When you call makeBox , you have to supply it with an object as its argument:

var anObject = { fullname: 'Someone with a name' }

makeBox(anObject);

Otherwise, myobj within your function will be undefined .

This code is completely valid provided "templates" is defined and you supply the argument "myobj" as an object:

function makeBox(myobj) {
    if (myobj.fullname.length > 18) {
        myobj.fullname = myobj.fullname.slice(0, 15);
        myobj.fullname = myobj.fullname + '...';
    }
    var box = templates.box.supplant(myobj);
    return box;
}
makeBox({
    fullname: "Jason Smith"
});

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