星期用中文展示
date函数的原型只能获取到数字的星期,但是使用场景中我们常见的是汉字,于是使用prototype对原型进行扩充
<script>
Date.prototype.getCnDay = function() {
return '星期' + '日一二三四五六'.charAt(this.getDay())
}
let d = new Date();
alert(d.getCnDay());
</script>
用原型封装tri-去除首尾空格
<script>
String.prototype.startTrim = function() {
let reg = /(^\s*|\s*$)/g;
return this.replace(reg, '');
}
let str = ' 123 ';
console.log( str.startTrim());
</script>
用原型封装检测数据类型
<script>
Object.prototype.type = function() {
// return Object.prototype.toString.call(this);//返回的是这种格式:[object String]
let str = Object.prototype.toString.call(this);
return str.substring(0, str.length - 1).split(' ')[1]; //处理后返回字符串:String
}
let str = 'aaaa';
let n = 123;
let b = true;
let fn = function() {}
console.log(str.type()); //string
console.log(n.type()); //number
console.log(b.type()); //boolean
console.log(fn.type()); //function
</script>