为什么 String.prototype 像标准对象一样记录它的对象,而 Array.prototype 像标准数组一样记录它的对象? [英] Why does String.prototype log it's object like a standard object, while Array.prototype logs it's object like a standard array?

查看:30
本文介绍了为什么 String.prototype 像标准对象一样记录它的对象,而 Array.prototype 像标准数组一样记录它的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单地说,为什么 String.prototype 使用标准的大括号和键值对记录字符串对象,而 Array.prototype 记录数组对象就像一个带有方括号和值的数组?

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, with square brackets and values?

String.prototype.test = function(){
    console.log(this); // logs { '0': 't', '1': 'e', '2': 's', '3': 't' }
};
var str = 'test';
str.test();
Array.prototype.test1 = function(){
    console.log(this); // [1,2,3,4]
};
var arr = [1,2,3,4];
arr.test1();

推荐答案

因为在方法调用中,this 参数总是(在草率模式下)转换为对象.你看到的是一个 String 对象,它是从 "test" 原始字符串值产生的.你调用方法的数组已经是一个对象,所以什么都没有发生,你只是像以前一样得到数组.

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"

这篇关于为什么 String.prototype 像标准对象一样记录它的对象,而 Array.prototype 像标准数组一样记录它的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆