Are object and string prototypes not prototypes of certain strings?

I am trying to understand how JavaScript-based prototype-based inheritance works. I expected the results below to be rated as true. Why is this?

var myStr = "Sample";
String.prototype.isPrototypeOf(myStr); // false
Object.prototype.isPrototypeOf(myStr); // false
+4
source share
3 answers

JavaScript has both primitive strings and string objects. What you wrote there is a primitive line. The method Object.prototype.isPrototypeOfalways returns falsefor any primitive, so your results make sense.

If you used a string object, you will get true:

var myStr = new String("Sample");
console.log(String.prototype.isPrototypeOf(myStr)); // true
console.log(Object.prototype.isPrototypeOf(myStr)); // true
Run codeHide result

, : , , String.prototype?

, , accessor , ( String.prototype ), . ( .)

, String.prototype, ( ):

Object.defineProperty(String.prototype, "foo", {
  value: function() {
    return this;
  }
});
var primitive = "string";
var object = primitive.foo();
console.log(primitive === object);                      // false
console.log(primitive == object);                       // true
console.log(String.prototype.isPrototypeOf(primitive)); // false
console.log(String.prototype.isPrototypeOf(object));    // true
Hide result
+4

, . , , String, :

var myStr = new String("Sample");
String.prototype.isPrototypeOf(myStr); // true
+2

, isPrototypeOf , , .

- String, ( !):

var myStr = new String("Sample");
console.log(String.prototype.isPrototypeOf(myStr)); // true
console.log(Object.prototype.isPrototypeOf(myStr)); // true
Hide result

- , .

.

var myStr = "Sample";
console.log(String.prototype.isPrototypeOf(Object(myStr))); // true
console.log(Object.prototype.isPrototypeOf(Object(myStr))); // true
Hide result
+2

Source: https://habr.com/ru/post/1663650/


All Articles