在 JS 中从一个方法调用另一个方法
我有以下 JS 片段
var Customer : function()
{
this.ShipProduct : function()
{
//Logic for shipping product. If shipping successful, notify user
//Here I am trying to call Notify
//this.Notify(); // does not work
}
this.Notify = function()
{
//Logic for notify
}
}
我如何从 ShipProduct 调用 Notify?
I have the following snippet of JS
var Customer : function()
{
this.ShipProduct : function()
{
//Logic for shipping product. If shipping successful, notify user
//Here I am trying to call Notify
//this.Notify(); // does not work
}
this.Notify = function()
{
//Logic for notify
}
}
How would I call Notify from ShipProduct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
那不是JS,那是语法错误的集合。
分配变量时使用
=
,简单对象内使用:
,不要混淆简单对象和函数,不要忘记逗号,不要在属性名称前添加 <代码>这个。。That is not JS, that is a collection of syntax errors.
Use
=
when assigning variables, and:
inside simple objects, don't confuse simple objects and functions, don't forget commas, and don't prefix property names withthis.
.这个例子看起来不错,除了第一行,冒号应该是等号。
我猜这个问题与您调用
ShipProduct
的方式有关。如果您这样做,一切都应该有效:但是,如果您分离该方法并直接调用它,它将不起作用。如:
这是因为 JavaScript 依赖于点表示法访问器来绑定
this
。我猜测您正在传递该方法,也许是传递给 Ajax 回调或其他东西。在这种情况下你需要做的就是将其包装在一个函数中。例如:
This example looks fine except for the first line, that colon should be an equal sign.
The problem, I'm guessing, has to do with how you're calling
ShipProduct
. If you're doing it like this, everything should work:However if you detach the method and call it directly, it won't work. Such as:
This is because JavaScript relies on the dot notation accessor to bind
this
. I'm guessing that you're passing the method around, perhaps to an Ajax callback or something.What you need to do in that case it wrap it in a function. Such as:
这似乎有效:
This seems to work:
怎么样:
这假设您想要公开这两个函数 - 如果
notify
仅由Customer
在内部使用,则无需公开它,因此您可以返回像这样:How about:
This assumes that you want to expose both functions -- if
notify
is only used byCustomer
internally, then there's no need to expose it, so you would instead return like so: