Phillip Senn
Phillip Senn

Reputation: 47605

Adding a property to a function

You can assign a property to a function, but is that a good idea? In this example, I'm showing that you can't create a property to a function inside the function, but you can outside it.

Q: Is a.questionable considered an ok JavaScript programming practice?

function a() {
a.bad = 1
}
a.questionable = 2

function d() {
  console.log(a.bad)
  console.log(a.questionable)
}
d()

This question was inspired by JavaScript: Understanding the Weird Parts

Upvotes: 1

Views: 222

Answers (2)

gyre
gyre

Reputation: 16777

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
)

Upvotes: 3

Ry-
Ry-

Reputation: 224913

It’s fine to put properties on functions. In fact, that’s exactly what static methods are on ES6 classes, which is the only use of static; consider it explicit language support.

class Foo {
    static bar() {}
}

'bar' in Foo  // true
typeof Foo    // 'function'

In this example, I'm showing that you can't create a property to a function inside the function, but you can outside it.

You can create a property on a function inside that function, but it’s unreasonable to expect the body of a function to run without calling it.

Upvotes: 3

Related Questions