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
.
Freezing an object prevents extensions and makes existing properties non-writable and non-configurable.
Freezing is the process that causes a substance to change from a liquid to a solid. Freezing occurs when the molecules of a liquid slow down enough that their attractions cause them to arrange themselves into fixed positions as a solid.
The difference between the JavaScript Object. freeze() and const is that the former prevents mutability whereas the latter doesn't prevent mutability.
In JavaScript, functions are called Function Objects because they are objects. Just like objects, functions have properties and methods, they can be stored in a variable or an array, and be passed as arguments to other functions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With