In this example, I'm showing that you can't create a property to a function inside the function, but you can outside it.
This is actually not the case. You can add properties to a function anywhere you have a reference to it. The problem is that you haven't called a()
and so the line a.bad = 1
has never had a chance to run.
function a() {
a.bad = 1
}
a.questionable = 2
function d() {
console.log(a.bad)
console.log(a.questionable)
}
a()
d()
Q: Is a.questionable
considered an ok JavaScript programming practice?
jQuery uses it quite extensively (think jQuery.fn
, jQuery.extend
, etc.) — so no, I don't think it is considered a "bad" programming practice per se. In fact, adding properties to a constructor function was the only way to mimic static fields and methods before ES6 introduced them as a part of class
syntax.
function Constructor() {
}
Constructor.staticMethod = function () {
return "I'm a static method!"
}
Constructor.staticProperty = "I'm a static property!"
console.log(
Constructor.staticMethod(),
Constructor.staticProperty
)