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
Yes, it is a function object. All objects in javascript can have properties, and so
$.fn.collapsehasdefaults.Your fiddle does not work because every function [object] has a non-writable
nameproperty which contains the name of the function – if it were named. You are assigning an anonymous function to themy_objectvariable, which has an empty name. Notice it is a string, notundefined! Have a look at http://jsfiddle.net/KTzUw/3/