从实例函数内部运行的同一个类中的另一个方法调用该类中的方法
问题描述:
我试图从 getUser
调用方法 clean
,但是它返回 undefined
。
如果我调用 u.test()
,则效果很好。
I am trying to call the method clean
from getUser
, but it returns undefined
.
If I call u.test()
, it works perfectly.
如何解决此问题
class User
constructor: () ->
@db = # connect to db...
clean: (user, callback) ->
delete user.password
callback user
getUser: (id) ->
@db.get id, (err, user) ->
@clean user, (u) -> console.log u
test: () ->
@clean {name: "test", password: "hello"}, (u) ->
console.log u
u = new User
u.getUser()
答
您需要 =>
作为内部函数。
在内部函数中,带有->的默认功能是绑定到 undefined
的普通函数。使用=>,可以将其绑定到函数实例化上下文的 this
值。
In your inner function, with ->, it's a normal function bound to undefined
by default. With =>, you bind it to the this
value of the function instantiation context.