I am trying to understand a third party Javascript code. But am not able to figure out what is the use of the below coding style.
function A(){
}
A.Prop = '23';
A.generate = function(n){
// do something
}
And then it is just used as :
A.generate(name);
Can someone explain what this code is doing. I understand some bit of OO Javascript, but i wonder if this is any other form of extending an object with new properties to it. Though i dont see any "new" keyword being used, to create an object.
Any ideas ?
Thanks,
An empty function is basically creating a function without defining any operations inside it. A class named Demo contains an empty function named 'my_empty_fun' which is just completed by placing two flower brackets, without adding any functionality into it.
The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it.
Use the length property to check if a string is empty, e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then it's empty, otherwise it isn't empty.
Use Object. Object. keys will return an array, which contains the property names of the object. If the length of the array is 0 , then we know that the object is empty.
They are creating a namespace. There are many ways to do this, and all are more-or-less equivalent:
A = {
Prop : '23',
generate : function (n) {
// do something
}
};
Or, equivalently:
A = { };
A.Prop = '23';
A.generate = function (n) {
// do something
};
Also, if you like being verbose:
A = new Object();
A.Prop = '23';
A.generate = function (n) {
// do something
};
function
is usually used to denote a "class" rather than a "namespace", like so:
A = (function () {
var propValue = '23'; // class local variable
return {
"Prop" : propValue,
"generate" : function (n) {
// do something
}
};
})();
// then I can use A in the same way as before:
A.generate(name);
It looks like they're using a dummy function to create a namespace.
You're right; this is useless.
They should use a normal object instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With