返回信息流我想给String类型实现一个函数,调用它会被加一个前缀,比如
let a = "aaa"
console.log(a.toAbc())
然后输出“abc:aaa”这样的效果
我的代码是这样的
```
"use strict"
String.prototype.toAbc = () => {
return "abc:" + this.toString()
}
let a = "aaa"
console.log(a.toAbc());
```
结果输出是
```
abc:[object Object]
```
那到底应该咋写呢?
这是一条镜像帖。来源:北邮人论坛 / java-script / #1364同步于 2017/2/12
该镜像源已超过 30 天没有更新,可能在源站已被删除。
JavaScript机器人发帖
一个似乎很简单的问题
sven
2017/2/12镜像同步5 回复
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
ES5实现:
String.prototype.toAbc = function(){return 'abc:' + this.toString();}
var a = 'aaa';
console.log(a.toAbc());
箭头函数不要瞎用,不是只要是ES6就非要用=>,也要分场景的
用=>就要明白this到底是谁?实例?window?undefined?
另外,扩充String本身就是不推荐的做法,ES6是有class的
class MyString {
constructor(value) {
this.value = value;
}
toAbc() {
return 'abc:' + this.value;
}
}
let a = new MyString('aaa');
console.log(a.toAbc());
OR
class MyString {
constructor(value) {
this.value = value;
}
toAbc = () => {
return 'abc' + this.value
}
}
let a = new MyString('aaa');
console.log(a.toAbc());
try them out on Babel:
https://babeljs.io/repl/
好,多谢,确实是我乱用了
【 在 logsin 的大作中提到: 】
: ES5实现:
: String.prototype.toAbc = function(){return 'abc:' + this.toString();}
: var a = 'aaa';
: ...................