how do some chemicals in plants protect them from their enemies
Through allelochemicals  that influence the behavior, growth, or survival of herbivores.
Plant defense against herbivory
Plant defense against herbivory or host-plant resistance (HPR) describes a range of adaptations evolved by plants which improve their survival and reproduction by reducing the impact of herbivores. Plants can sense being touched, and they can use several strategies to defend against damage caused by herbivores. Many plants produce secondary metabolites, known as allelochemicals, that influence the behavior, growth, or survival of herbivores. These chemical defenses can act as repellents or toxins to herbivores, or reduce plant digestibility.

wiki:15820269
Plant defense against herbivory [SEP] Introduction
Another approach diverts herbivores toward eating non-essential parts, or enhances the ability of a plant to recover from the damage caused by herbivory. Some plants encourage the presence of natural enemies of herbivores, which in turn protect the plant. Each type of defense can be either "constitutive" (always present in the plant), or "induced" (produced in reaction to damage or stress caused by herbivores). Historically, insects have been the most significant herbivores, and the evolution of land plants is closely associated with the evolution of insects. While most plant defenses are directed against insects, other defenses have evolved that are aimed at vertebrate herbivores, such as birds and mammals.