Wonderjar's Blog

JS toString方法详说

2018-07-12

基本用法

Object.prototype.toString

1
2
3
var o = new Object();
o.toString();
// [object Object]

Function.prototype.toString

1
2
3
var fn = function(x) {return x;}
fn.toString()
// "function (x){return x;}"

String.prototype.toString

1
2
3
var x = new String("Hi"); 
x.toString()
// "Hi"

Array.prototype.toString

1
2
3
4
5
arr = ['a', 'b'];
x = arr.toString()
y = arr.join(',')
// The above two expressions are equivalent, both return:
// "a,b"

Number.prototype.toString

1
2
3
4
5
6
7
8
9
10
11
12
var count = 10;

console.log(count.toString()); // displays '10'
console.log((17).toString()); // displays '17'

var x = 6;

console.log(x.toString(2)); // displays '110'
console.log((254).toString(16)); // displays 'fe'

console.log((-10).toString(2)); // displays '-1010'
console.log((-0xff).toString(2)); // displays '-11111111'

一些有意思的用法

判断类型

1
2
3
4
5
6
7
8
9
var toString = Object.prototype.toString;

toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]

//Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]

获取函数名,函数形参列表,函数源代码

利用Function.protoype.toString,加上正则匹配,其实能取到很多东西

1
2
3
4
5
6
var rArgs = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
function getParamNames( fn ){
var argStr = fn.toString().match(rArgs)[1].trim();
return argStr? argStr.split(/\s*,\s*/): [];
}
getParamNames(function( $scope, greeter ){})

甚至在es6的Template String之前,可以这样藏一段多行文本在函数中,

1
2
3
4
5
6
7
8
9
10
11
var rComment = /\/\*([\s\S]*?)\*\//;
// multiply string
function ms(fn){
return fn.toString().match(rComment)[1]
};
ms(function(){/*
<div>
<h2>{blog.title}</h2>
<div class='content'>{blog.content}</div>
</div>
*/})

和Webworker中利用Blob结合

1
2
3
4
5
6
7
8
9
function workerify(fn) {
var worker = new Worker(
URL.createObjectURL(new Blob([
'self.onmessage = ' + fn.toString()], {
type: 'application/javascript'
})
));
return worker
}

和Eval结合

可以让一个被toString的函数,重新得到声明(没想到有啥用…)