clarifying example code

An interesting question may arise in the example above: what’s the value of this inside set fullName(value)? Where are the properties this.name and this.surname written: into user or admin?

The answer is simple: this is not affected by prototypes at all.

No matter where the method is found: in an object or its prototype. In a method call, this is always the object before the dot.

So, the setter call admin.fullName= uses admin as this, not user.

That is actually a super-important thing, because we may have a big object with many methods, and have objects that inherit from it. And when the inheriting objects run the inherited methods, they will modify only their own states, not the state of the big object.

The example code doesn't show these concepts. Also, these additions can make readers ask questions before the explanation of the example code.
This commit is contained in:
Mustafa Kemal Tuna 2020-07-25 05:38:45 +03:00 committed by GitHub
parent 8e1f438a5b
commit 7d0d65478d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -197,6 +197,9 @@ alert(admin.fullName); // John Smith (*)
// setter triggers! // setter triggers!
admin.fullName = "Alice Cooper"; // (**) admin.fullName = "Alice Cooper"; // (**)
alert(admin.fullName); // Alice Cooper , state of admin modified
alert(user.fullName); // John Smith , state of user protected
``` ```
Here in the line `(*)` the property `admin.fullName` has a getter in the prototype `user`, so it is called. And in the line `(**)` the property has a setter in the prototype, so it is called. Here in the line `(*)` the property `admin.fullName` has a getter in the prototype `user`, so it is called. And in the line `(**)` the property has a setter in the prototype, so it is called.