Why does 'this' inside String.prototype refer to the type of the object and not the type of the string?

I am trying to expand the string to provide the hash itself. I use the cryptographic library Node.js.

I continue the line as follows:

String.prototype.hashCode = function() { return getHash(this); }; 

and I have a getHash function that looks like this:

 function getHash(testString) { console.log("type is" + typeof(testString)); var crypto = require('crypto'); var hash = crypto.createHash("sha256"); hash.update(testString); var result = hash.digest('hex'); return result; } 

The function works fine when called directly, as in

 var s = "Hello world"; console.log(getHash(s)); 

but when trying:

 var s = "ABCDE"; console.log(s.hashCode()); 

method call is not performed. It looks like this in String.prototype.hashCode identified as an object when crypto.hash.update is crypto.hash.update , but a string is expected. I thought this inside String.prototype would be the string itself, but for some reason it looks like a getHash() object. How can i fix this?

+5
source share
2 answers

this cannot be a primitive type outside strict mode , so it becomes a String wrapper type that does not behave like a primitive string at all (in particular, like typeof and equality - both strict and free). You can use it:

 String.prototype.hashCode = function () { return getHash( '' + this); }; 

where '' + used to pass any value to a primitive string. ( String(this) also works if you feel it is clearer.)

You can also go into strict mode, where everything makes sense:

 String.prototype.hashCode = function () { 'use strict'; return getHash(this); }; 
+7
source

When you call a method on a variable of a primitive type, so-called automatic boxing occurs. This process wraps a primitive value in the corresponding object, for example, 'asdf' - new String('asdf') . Since technically primitive values ​​do not have methods and properties, they are placed in object prototypes. With automatic boxing, you can call methods for primitive values. And inside the method, this always an object that has this method.

If you want to access a primitive value in a method, you can either pass it as an argument, or you want to get a primitive value from this . For instance:

 var str = new String('asdf') // String {0: "a", 1: "s", 2: "d", 3: "f", length: 4, formatUnicorn: function, truncate: function, splitOnLast: function, [[PrimitiveValue]]: "asdf"} String(str) // 'asdf' var num = new Number(123) // Number {[[PrimitiveValue]]: 123} Number(num) // 123 var bool = new Boolean(true) // Boolean {[[PrimitiveValue]]: true} Boolean(bool) // true 
+2
source

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


All Articles