The cause of

It is well known that basic types such as var STR = ‘hello’; The STR in can call all String methods.

Many articles have interpreted this behavior as an automatic boxing mechanism, similar to the following workflow:

var str = 'hello'; var index = str.indexOf('h'); Var temp = new String(STR); var index = temp.indexOf('h'); temp = null;Copy the code

This is an easy pattern to understand, of course, but if creating a String every time a method is called in the same context is too poor performance, and browsers really do work this way. Using Chrome as an example (different kernel browsers behave differently), I started to explore.

explore

Hijack new String

Initially, I wanted a way to see if the browser really did new a String when it executed the String method. Through exploration I found the following way,

var bind = Function.bind;
var unbind = bind.bind(bind);

function instantiate(constructor, args) {
    return new (unbind(constructor, null).apply(null, args));
}

String = function (String) {
    MyString.prototype = String.prototype;

    return MyString;

    function MyString() {
        console.log('new String');
        var str = instantiate(String, arguments);
        return str;
    }
}(String);

var copyFunc = String.prototype.indexOf;
String.prototype.indexOf = function (s) { console.log('My indexOf', this.valueOf(), arguments); return copyFunc.call(this.valueOf(), s); }

var a = '123';
console.log(a.indexOf('1'));
console.log(a.indexOf('2'));
Copy the code

After Chrome executes, we find that when we use indexOf, there is no new String. However, indexOf on the String prototype chain does get called, indicating that V8 can use the String method without creating a complete String object.

Other information

With an interest in understanding the purpose of v8’s mechanics here, I found some resources from javascripts. Info and StackOverflow.

Mentioned in the article on basic types in javascript.info.

StackOverflow is even clearer. It depends a lot on the implementation of the engine, he says, trying to explain how it works using V8 as an example. A String of primitive type in V8 is parsed as V8 ::String, and methods can be called directly.

conclusion

When reviewing this little knowledge from MDN to the original data, I saw a sentence that the basic type is neither object nor method data, which triggered my thinking.

Through information verification and learning, the understanding of this section has become more clear, the implementation of v8 also feel less mysterious, ^_^!