什么时候在javascript OO中使用它? [英] When to use this in javascript OO?

查看:77
本文介绍了什么时候在javascript OO中使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript OO中,什么时候应该使用this关键字?

In Javascript OO, when should I use the this keyword?

此外,如果我想从同一个类的另一个方法中调用一个类的方法,我应该使用this还是仅使用函数名称?例如,这是正确的吗?

Also, if I want to call a method of a class from another method of the same class, should I use this or just the name of the function? E.g is this correct?

function Foo()
{
   this.bar= function()
   {
      alert('bar');
   }

   this.baz= function()
   {
     this.bar(); //should I use this.bar() or just bar()?
   }
}

推荐答案

当涉及面向对象" JavaScript时,这里有一个不错的指南Mark Dickinson在SO上链接到:

When it comes to "object-oriented" JavaScript, here's a nice guide Mark Dickinson here on SO linked to: Private Members in JavaScript. It does go into detail about some other stuff you don't really need now, but once you understand how JavaScript works, you'll see that it's quite different from your ordinary object-oriented language when it comes to things like what this really means.

我要说的是,您绝对应该使用this,但是也许您的函数应该在类"的prototype部分中(这样可以避免在每次创建新实例时重新定义函数) )

I'd say that in your case, you should definitely use this, but maybe your functions should be in the prototype part of your "class" (this avoids redefining the function every time a new instance is created.)

这篇关于什么时候在javascript OO中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆