Angel Politis Angel Politis - 2 months ago 5
Javascript Question

Why can I not change the prototype of a string?

Let's suppose we have the following code, where for some reason I want stubbornly to change the prototype of

a
,
b
and
c
to the prototype of
Obj
.

Question: Why will the object and the array accept the change of prototype, but the string won't?



var Obj = function() {}

Obj.prototype = {
log: function(s) {
console.log(s);
}
}

var
a = {1110: "1110"},
b = [1110],
c = "1110";

Object.setPrototypeOf(a, Obj.prototype);
Object.setPrototypeOf(b, Obj.prototype);
Object.setPrototypeOf(c, Obj.prototype);

a.log("shuh");
b.log("shuh");
c.log("shuh");




Answer

That's because "1110" is not an object, but of a primitive string type. So it does not have a notion of prototypes.