据我所知,函数和对象应该是javascript中的引用类型。因此,如果我得到了一个对象,在我的代码中,这个对象发生了变化,它应该会不可避免地影响到它的所有参照物。但在下面的例子中,它并没有发生:
Myobject = {
key1: 123,
key2: function() {return this.key1}
}
f = Myobject.key2;
Myobject.key2 = function() {return 'test'};
f();key2的行为类似于primitve类型,通过它的引用来保持key2的inital状态。那么,这种数据类型的机制在javascript中工作得如何巧妙呢?
发布于 2015-03-08 16:47:59
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 windowhttps://stackoverflow.com/questions/28929064
复制相似问题