从我读过的函数和对象应该是javascript中的引用类型。因此,如果我有一个对象并且在我的代码中,并且这个对象发生了变化,那么它应该会立即影响对它的所有引用。但在下面的例子中它并没有发生:
Myobject = {
key1: 123,
key2: function() {return this.key1}
}
f = Myobject.key2;
Myobject.key2 = function() {return 'test'};
f();
key2的行为类似于原始类型,如果它发生变化,则通过其引用保留key2的初始状态。那么这种数据类型的机制在javascript中是如何工作的呢?
答案 0 :(得分:0)
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