[英]Is function object created by `new` constructor treated as mutable object in javascript?
From study, I understood that in javascript, mutable objects () are treated by call-by-reference , and immutable objects are treated by call-by-value calling convention. 从学习,我明白,在JavaScript中, 可变对象 ()是由呼叫通过引用处理, 不可变对象是通过调用传值调用约定处理。
Let's say I use this kind of data, 假设我使用这种数据,
var Node = function(data) {
this.data = data;
this.next = null;
};
var v = new Node(0);
is v
a mutable object or an immutable object?? v
是可变对象还是不可变对象?
JavaScript don't have "immutable objects" there 2 types: JavaScript没有2种类型的“不可变对象”:
1) primitives - immutable 1)原语-不可变
2) Object - mutable 2)对象-可变的
update: object freeze can give some "immutable" 更新: 对象冻结可以产生一些“不变”
It is mutable, as you can see from this working example. 从这个工作示例中可以看出,它是可变的。
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);
First of all lets understand what is the new
operator doing inside the created execution context behind the scenes: 首先,让我们了解
new
操作员在幕后创建的执行上下文中正在做什么:
It will: 它会:
this
label) this
标签上) __proto__
property will reference the function's prototype
property __proto__
属性将引用该函数的prototype
属性。 So in your case: 因此,在您的情况下:
var v = new Node(0);
v
is actually an Object
(the one that created and returned via new
) and objects in JavaScript are mutable. v
实际上是一个Object
(通过new
创建和返回的对象),JavaScript中的对象是可变的。
Here are the primitives (immutable) types: 以下是基元(不可变)类型:
Boolean 布尔
Null 空值
Undefined 未定义
Number 数
String 串
Symbol (new in ECMAScript 6) 符号(ECMAScript 6中的新增功能)
v
is a mutable object. v
是可变对象。 To change this object to an immutable object use the Object.freeze()
method. 若要将此对象更改为不可变的对象,请使用
Object.freeze()
方法。
Example: 例:
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.
Object.freeze()方法冻结对象。 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
Frozen()返回传入的对象。 更多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.