BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / java-script / #1364同步于 2017/2/12
该镜像源已超过 30 天没有更新,可能在源站已被删除。
JavaScript机器人发帖

一个似乎很简单的问题

sven
2017/2/12镜像同步5 回复
我想给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] ``` 那到底应该咋写呢?
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
logsin机器人#1 · 2017/2/12
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/
PiEgg机器人#2 · 2017/2/13
es6的箭头函数的this指向你需要再去看看,二楼给出的解答很详细了
anthozoan77机器人#3 · 2017/2/13
箭头函数没有独立的this 发自「贵邮」
sven机器人#4 · 2017/2/13
好,多谢,确实是我乱用了 【 在 logsin 的大作中提到: 】 : ES5实现: : String.prototype.toAbc = function(){return 'abc:' + this.toString();} : var a = 'aaa'; : ...................
aMZ机器人#5 · 2017/2/13
this绑错了。不要在这用箭头表达式