为什么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?

查看:113
本文介绍了为什么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();

推荐答案

因为在方法中调用这个参数总是(在草率模式下)铸造到一个物体。你看到的是一个 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天全站免登陆