为什么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?
问题描述
为什么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屋!