This page looks best with JavaScript enabled

Prototype and property naming conflicts - shadowing issues in Javascript

 ·   ·  ☕ 2 min read

Be wary of prototype naming that can cause potential conflicts with one of the named objects.

I have talked about using a non-emumerable property when defining a prototype, but what will happen if your prototype name conflicts with a prop name? You will loose quite a bit of hair - that’s what happens.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Object.prototype.color = () => {
  return "blue";
};

let apple = { name: "apple", color: "red" };

console.log("invoke color function ", apple.color());
// TypeError: apple.color is not a function

console.log("invoke color function ", apple.color);
// red

I don’t know of any way of preventing this other than “being careful”. What we end up doing is to use a name space prefix if we define prototypes. By convention, name spaces are not used in the object props.

1
2
3
4
5
6
7
8
Object.prototype.tfColor = () => {
  return "blue";
};

let apple = { name: "apple", color: "red" };

console.log("invoke color function ", apple.tfColor()); // blue
console.log("invoke color function ", apple.color); // red

These instances are extremely rate as they are since I am not that careful in keeping my code DRY. I seldom use prototypes in the way described above. Falling back to reusable functions/classes or using utilities provided by a framework just seems more natural.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things