javascript - var card= cleanNum: function(){....} what does this cleanNum: mean? -
i want know cleannum means in following code. function name or represent else?
//code snippet 1 var creditcard = { cleannum : function(number){ return number.replace(/[- ]/g,""); } };
q1. not meaning of cleannum. can please explain significance of cleannum().
q2. if using in function called another_func(), how call code snippet 1?
is below code snippet same above?
//code snippet 2 function cleannum(number){ //sample code }
first thing´s first: var x = {}
defines new object, every variable declared within {} becomes field of object.
the following create object (referenced variable creditcard
) field number
var creditcard = { number: '3432-2342-34243' };
so q1, significance of cleannum, it's member of of object creditcard
. instead of containing int/string/date etc, contains function
var creditcard = { cleannum : function(number){ return number.replace(/[- ]/g,""); } };
as q2, function same, scope not. when defined directly, it's accessible directly, if defined inside object, it's accessible through object:
creditcard.cleannum(somenumber);
to go step further, demonstrate function function, define function outside of creditcard , reuse function inside object:
function cleannumglobal(number){ return number.replace(/[- ]/g,""); } var creditcard = { cleannum : cleannumglobal }; //both call same function: console.log(cleannumglobal('2432-2423-234')); console.log(creditcard.cleannum('2432-2423-234'));
as side note: function such this, use properties of object itself, instead of using parameter number, use property number
of object (or clean number upon setting property). besides question scope ;)
Comments
Post a Comment