0

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");

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

So, we can only change the prototype of objects; not of everything under the sun, right? Thanks @zerkms.
@AngelPolitis yep, in JS only objects have prototypes.
1

You can't change the prototype of a string primitive, because only objects have a [[SetPrototypeOf]] internal method. This makes sense because the prototype determines property inheritance, but primitive values don't have properties, neither own nor inherited.

However, you can still change the prototype of a string object:

var Obj = function() {}

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

var a = {1110: "1110"},
    b = [1110],
    c = new String("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");

Comments

1

You can add log method to Object.prototype and all object will have it. This way you don't have to create separate log prototype for your objects, numbers and string, ... Here is an example of doing it

'use strict'
console.clear()

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

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

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

2 Comments

"Because all data types in JavaScript inherit from Object" --- that's not correct.
Types themselves don't inherit, they are not values. Did you mean values from all types? But only objects do inherit, and not necessarily from Object.prototype.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.