Mutating context in member functions

#1

If I define some type like:

type Foo {
field: int
bar: member function()
}

and then inside the bar implementation i modify ‘this’ (i.e. the calling context)
function bar() {
this.field = 2;
}

will the calling context be modified in the calling scope?
var f = Foo.make({field:1});
f.bar()
// f.field == 2 OR f.field == 1

0 Likes

#2

Courtesy of John Coker, Senior Architect:

The lifetime of an Obj instance is unrelated to functions that you call on it. If you call two different member functions in the same context on the same instance, they will both have that same instance as this, so the lifetime will encompass both calls. If the first call sets a field to a different value, it’s the same Obj instance so the second call will see that changed value. In your code example, the value of foo.field will be 2 after the call to bar returns. However, if bar is executed in a different context than your script, then the value will be 1. It also gets more complicated for persistable instances, because a change without an update will be lost the next time the object is loaded.

0 Likes

Type instances not mutated when using member functions