SimplGy
SimplGy

Reputation: 20437

Is there any reason to Object.freeze a function?

I understand the point of recursing over a deep object to do a shallow Object.freeze on every child property of it. What is the point of freezing a function object's value? The reference is already frozen because of the shallow freeze at a higher level--is it possible to mutate the function object's value itself?

Example:

// Library Function [deepFreeze source](https://github.com/substack/deep-freeze/blob/master/index.js)
function deepFreeze (o) {
  Object.freeze(o); // shallow freeze the top level
  Object.getOwnPropertyNames(o).forEach(function (prop) {
    if o[prop] != null // no point freezing null or undefined
    && (typeof o[prop] === "object" || typeof o[prop] === "function") {
      deepFreeze(o[prop]);
    }
  });
  return o;
};

// Usage
var x = {
  y: [1,2,3],
  z: function(){}
};
deepFreeze(x);

Just trying to see if there's something fundamental I don't understand here or if this is just protecting against mutating the function object, eg: x.z.foo = 3.

Upvotes: 8

Views: 3119

Answers (1)

SimplGy
SimplGy

Reputation: 20437

In Javascript, functions are objects. This I knew.

All of the native properties of the function object (except prototype) are already immutable:

var x = function(foo){}
Object.getOwnPropertyNames(x)
// ["length", "name", "arguments", "caller", "prototype"]
x.length; // 1, because there is one argument
x.length = 2;
x.length; // still 1.

But you can, of course, add other properties:

x.foo = 3;
x.foo; // 3

But I think using a function as a data structure is extremely uncommon.

The comment that really resonates with me is Jared's:

Its kinda pointless, but even more pointless to write code that treats functions differently than other objects.

People can add whatever properties they want to a function object, and in some cases that might be a reasonable solution, but I think it's typically unexpected to store values there. However, writing a library function to treat functions differently than any other object gains nothing.

Conclusion: lock the function object down just like a regular object because why not, and also it closes a corner case where someone might put a value on it.

Upvotes: 4

Related Questions