Someone taught him. Rumple knew how to do it as well and I doubt he learned that from Pan. Rumple’s shadow definitely had a personality and we know that Pan’s does as well, just not what kind. Perhaps his shadow taught him how to do it? He WAS looking for friends after all… maybe his shadow took on its own personality because Pan was going nuts?