由 `new` 构造函数创建的函数对象是否被视为 javascript 中的可变对象?

Is function object created by `new` constructor treated as mutable object in javascript?

通过学习,我了解到在 javascript 中, 可变对象 () 由 按引用调用 处理和 不可变对象按值调用 调用约定处理。

假设我使用这种数据,

var Node = function(data) {
  this.data = data;
  this.next = null;
};

var v = new Node(0);

v是可变对象还是不可变对象??

JavaScript 没有 "immutable objects" 有两种类型:

1) 基元 - 不可变

2) 对象 - 可变

更新:object freeze可以给一些"immutable"

它是可变的,正如您从这个工作示例中看到的那样。

var Node = function(data) {
  this.data = data;
  this.next = null;
};

var v = new Node(0);

v.myNewAttribute = 'foobar';

var elemDiv = document.createElement('div');
elemDiv.innerHTML = JSON.stringify(v);
document.body.appendChild(elemDiv);

首先让我们了解 new operator 在幕后创建的执行上下文中做了什么:

它将:

  1. 创建一个新对象(并将其附加到 this 标签)
  2. 新对象的 __proto__ 属性 将引用函数的 prototype 属性
  3. 它将 return 新创建的对象(如果您没有明确 returning 一个对象)

所以在你的情况下:

var v = new Node(0);

v 实际上是一个 Object(通过 new 创建并 return 的对象)并且 JavaScript 中的对象是可变的。

Here 是原始(不可变)类型:
布尔值

未定义
人数
字符串
符号(ECMAScript 6 新增)

v 是一个 可变的 对象。要将此对象更改为 不可变 对象,请使用 Object.freeze() 方法。

示例:

var Node = function(data) {
  this.data = data;
  this.next = null;
};

var v = new Node(0); // "v" object is mutable  
v.data = 1;          // The "data" property value will change
console.log(v);

Object.freeze(v); // "v" object is immutable  

v.data = 2;       // The "data" property value will NOT change

console.log(v);

The Object.freeze() method freezes an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. In addition, freezing an object also prevents its prototype from being changed. freeze() returns the same object that was passed in. more