Why does String.prototype log it's object like a standard object, while Array.prototype logs it's object like a standard array?

前端 未结 1 1380
礼貌的吻别
礼貌的吻别 2020-12-04 04:04

Simply why does String.prototype log the string object with the standard curly brackets and key value pairs, and the Array.prototype log the array object just like an array,

相关标签:
1条回答
  • 2020-12-04 04:43

    Because in a method call the this argument is always (in sloppy mode) casted to an object. What you see is a String object, which was produced from the "test" primitive string value. The array on which you call your method is already an object, so nothing happens and you just get the array as before.

    If you use strict mode, this cast doesn't happen:

    String.prototype.test = function() {
        "use strict";
        console.log(this);
    };
    var str = 'test';
    str.test(); // logs "test"
    
    0 讨论(0)
提交回复
热议问题