似乎行为与引用类型不同的引用类型

Reference types which doesnt seem to behave like reference types

本文关键字:引用类型      更新时间:2023-09-26

从我所读到的内容来看,函数和对象应该是javascript中的引用类型。因此,如果我在我的代码中得到了一个对象,并且这个对象发生了变化,它应该会立即影响对它的所有引用。但在下面的示例中,它不会发生:

Myobject = {
  key1: 123,
  key2: function() {return this.key1}
}
f = Myobject.key2;
Myobject.key2 = function() {return 'test'};
f();
key2

的行为类似于基元类型,如果 key2 发生更改,则通过其引用保留其初始状态。那么这种数据类型机制在javascript中是如何工作的呢?

f = Myobject.key2;

这样做f指向分配给key2的函数我们称之为"原始函数"。

Myobject.key2 = function() {return 'test'};

这样做是key2指向另一个函数 - 一个不影响f指向的操作,它仍然是"原始函数"。

可视化:

// key2 = undefined
// f    = undefined
Myobject = {
  key1: 123,
  key2: function() {return this.key1}
}
// key2 = function() {return this.key1}
// f    = undefined
f = Myobject.key2;
// At this point, they point to the same function
// key2 = f = function() {return this.key1}
Myobject.key2 = function() {return 'test'};
// At this point, you changed key2 but f still points to the original function
// key2 = function() {return 'test'};
// f    = function() {return this.key1}
f(); 
// possibly "undefined" because this = window if called this way
// and there's possibly no key1 on window