moey
moey

Reputation: 10887

Adding New Properties to a Function Object

I am trying to understand the following pattern:

// https://github.com/twitter/bootstrap/blob/master/js/bootstrap-collapse.js

  $.fn.collapse = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('collapse')
        , options = typeof option == 'object' && option
      if (!data) $this.data('collapse', (data = new Collapse(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.collapse.defaults = {
    toggle: true
  }

It looks like collapse is a function object. Then, why defaults can be added as a property to collapse?

The following (jsFiddle) snippet tries to add a new property to a function object but to no avail. What is it?

var my_object = function () {
    alert('Hello World!');
};
my_object.name = 'my_object';

console.log(my_object.name);  // prints an empty string

Upvotes: 2

Views: 122

Answers (3)

Alex Wayne
Alex Wayne

Reputation: 187034

.name is special, most other property names work:

var my_object = function () {
    alert('Hello World!');
};
my_object.someprop = 'my_object';
console.log(my_object.someprop);  // prints an empty string

The name property of functions is reserved.

function foo() {};
console.log(foo.name); // "foo"

In your case it's an empty string because it's declared as an anonymous function:

var foo = function() {};
console.log(foo.name); // ""

But other than a few reserved property names, yes, you can assign properties of functions like you can any object. This can be pretty powerful, as it lets you sort of tie data to the code that needs that data in a pretty clean way.

Upvotes: 2

jAndy
jAndy

Reputation: 236022

name is a reserved property for function instances and has non-configurable and non-writable flags, you can't overwrite it. Beside from that, a function does also inherit from Object and may have properties.

var my_fnc = function() { };

my_fnc.foobar = 42;

console.log( my_fnc_foobar ); // 42

Upvotes: 1

Bergi
Bergi

Reputation: 664528

Yes, it is a function object. All objects in javascript can have properties, and so $.fn.collapse has defaults.

Your fiddle does not work because every function [object] has a non-writable name property which contains the name of the function - if it were named. You are assigning an anonymous function to the my_object variable, which has an empty name. Notice it is a string, not undefined! Have a look at http://jsfiddle.net/KTzUw/3/

Upvotes: 2

Related Questions