关于NetLogo中self与myself动态作用域的技术问询
self Points to Patches (Not Turtle 0) in NetLogo's ask patches Blocks Great question—this is a common point of confusion when moving from Java to NetLogo, since the two languages have totally different design priorities. Let’s break this down clearly:
First, let’s confirm what’s happening
When you run code like this:
ask turtle 0 [ ask patches [ print self ; Outputs the current patch (e.g., (0 0), (1 0), etc.) print myself ; Outputs turtle 0 every time ] ]
You’re seeing exactly the intended behavior in NetLogo. Here’s why:
NetLogo’s self is tied to the current execution context
NetLogo is an agent-based modeling language—its entire design revolves around making it easy to define behavior for different types of agents (turtles, patches, the observer).
selfalways refers to the agent that is currently running the code block. When you useask patches, you’re telling every patch to execute the inner code one by one (or in parallel, depending on your settings). So for each iteration of that block, the "current agent" is a patch—henceselfpoints to that patch.myselfrefers to the agent that initiated theaskcommand. In this case, turtle 0 is the one callingask patches, somyselfstays tied to turtle 0 no matter which patch is running the inner block.
How this differs from Java’s this
Java’s this (even in lambdas/anonymous functions) is tied to the object that defines the function, not the context where it’s executed. That makes sense for Java’s object-oriented paradigm, where functions are tightly coupled to the objects they belong to.
NetLogo doesn’t work that way because it’s not focused on object methods—it’s focused on agent behaviors. When you switch agent contexts with ask, you want the code inside to operate on the target agent directly. Using self to refer to the current executing agent makes it trivial to write clean, intuitive modeling code like:
ask patches [ if self = patch 0 0 [ set pcolor red ] ; Targets exactly the (0,0) patch ]
Without this design, you’d have to pass explicit references to each patch, which would clutter up your code and make it harder to reason about agent behavior.
The bottom line
NetLogo’s self is designed to prioritize clarity and ease of agent-based modeling. It’s not trying to mimic Java’s this—it’s solving a different problem: making it immediately obvious which agent is acting at any point in your code.
内容的提问来源于stack exchange,提问作者RussAbbott

