简体   繁体   English

什么时候在javascript OO中使用它?

[英]When to use this in javascript OO?

In Javascript OO, when should I use the this keyword? 在Javascript OO中,我何时应该使用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? 另外,如果我想从同一个类的另一个方法调用类的方法,我应该使用this还是只使用函数的名称? Eg is this correct? 这是对的吗?

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

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

When it comes to "object-oriented" JavaScript, here's a nice guide Mark Dickinson here on SO linked to: Private Members in JavaScript . 谈到“面向对象”的JavaScript,这里有一个很好的指南Mark Dickinson在这里链接到: 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. 它确实详细介绍了其他一些你现在并不需要的东西,但是一旦你理解了JavaScript的工作原理,你会发现它与普通的面向对象语言完全不同,就像this真正意味着什么一样。 。

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.) 我会说,在你的情况下,你肯定应该使用this ,但也许你的函数应该在你的“类”的prototype部分(这避免了每次创建新实例时重新定义函数。)

In this particular instance, it's best to use a self-referencing variable in the place of this to prevent confusion and headaches inside functions. 在这个特定的例子中,最好使用自引用变量来代替this以防止在函数内部产生混淆和麻烦。

function Foo()
{
   var self = this;

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

   this.baz= function()
   {
     self.bar();
   }
}

The reason for it is because since everything in javascript is an object, the this keyword inside a function refers to the parent function. 原因是因为javascript中的所有内容都是对象,函数内的this关键字指的是父函数。 By defining a variable at a certain scope, your guaranteed that variable will maintain its scope. 通过在某个范围内定义变量,您保证该变量将保持其范围。

Just to stress and empathize previous answer of @tj111 I suggest you to read this . 只是为了强调和同情@ tj111之前的回答,我建议你阅读这篇文章 To better understand function scoping. 更好地理解功能范围。

The correct version is the one that doesn't give an error when you try to call the function. 正确的版本是在您尝试调用该函数时不会出错的版本。 If you omit this you will get a ReferenceError exception. 如果省略this您将收到ReferenceError异常。

In another post about 'function aliasing' in JavaScript, I explained in detail, with examples, how 'this' works in JavaScript. 在另一篇关于JavaScript中的“函数别名”的文章中,我通过示例详细解释了“这个”在JavaScript中是如何工作的。 I think it may be useful to you. 我认为它可能对你有用。

Please check: JavaScript function aliasing doesn't seem to work 请检查: JavaScript函数别名似乎不起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM