A common joke form exploits an ambiguous expression E. Prior likelihood or the preceding context in the joke favors one understanding for E, but then fresh context (in the joke) brings out another, more surprising one. The effect is that the sense of E has shifted as the joke proceeds. It’s a pun, son. Used in a sense-shifting pun joke. (Puns get used in all sorts of jokes: knock-knock jokes, one type of riddle joke, and more.)
I now offer two examples that especially tickled me, to show how such ((phonologically) perfect) puns work. Then some comments on a different joke form, formula pun jokes, which can turn on imperfect puns and involve a different kind of set-up / pay-off from sense-shifting pun jokes.