Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

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

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...