从实例函数内部运行的同一个类中的另一个方法调用该类中的方法 [英] Call method in class from another method in same class which is running inside a instance function
本文介绍了从实例函数内部运行的同一个类中的另一个方法调用该类中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图从 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.
这篇关于从实例函数内部运行的同一个类中的另一个方法调用该类中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文