简体   繁体   English

Object.freeze是否有任何理由使用函数?

[英]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. 我理解在深度对象上Object.freeze在它的每个子属性上执行浅的Object.freeze 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: xzfoo = 3 . 只是试着看看有什么基本的我在这里不理解,或者这只是防止变异函数对象,例如: xzfoo = 3

In Javascript, functions are objects. 在Javascript中,函数是对象。 This I knew. 我知道这个。

All of the native properties of the function object (except prototype ) are already immutable: 函数对象的所有本机属性( prototype除外)都是不可变的:

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. 结论:将函数对象锁定为像常规对象一样,因为为什么不这样做,并且还关闭了某人可能会在其上放置值的极端情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM