It's partially based off trees, according to Bulbapedia. Lightning is attracted to trees, explained briefly here:
Trees attract lightning because they provide a path for lightning to travel from the storm cloud to the earth.
Lightning rods are also intended to attract lightning. Any electricity sent towards Mega Sceptile is very likely just attracted to the tree part of it, rendering the Sceptile itself immune to Electric attacks.
From a gameplay perspective, Game Freak may have just wanted to give Mega Sceptile a potentially decent Ability in Doubles.
Hope I helped!