简体   繁体   中英

Assigning 'this' to a variable in Javascript

I'm taking an object oriented approach with Javascript, for two reasons. One, because it helps me learn, and two, just in case my code is to be distributed.

I already have assigning functions to variables and using this for public variables. I'm running into problems using this , however. When I'm in a "private" function, this refers to a different scope, and I can't access the variables under this . I'll illustrate my point.

var ClassObject = function() {
  this.var1 = 'Hello';

  var var2 = 786;

  this.func1 = function() {
    alert(this.var1); // Alerts Hello
    alert(var2); // Alerts 786
  }

  var func2 = function() {
    alert(this.var1); // Alerts undefined
    alert(var2); // Alerts 786
  }
}

The only way I've found to give func2 access to this.var1 was to make another variable assigned to this : var c = this . Is this the best way to go about this task, or even widely acceptable? Can anybody offer a better solution?

Thank you all.

Yes, this is accepted practice. See this article on scope or this question .

Reading up on closure may also be helpful.

The value of this is set by the javascript interpreter on every single function call including when calling your private functions. The rules are fairly simple:

  1. If calling object.method() , then this is set to the object inside the method.
  2. If calling a normal function (whether global or local) like fn() , this is set to the global object (which is usually window in a browser).
  3. When using .apply() or .call() , this is set to the first argument to those functions (eg you can control what it is set to by what you pass to .apply() or .call() .

Thus, when you call your private functions, you're getting option 2. If you want access to the this of your object, you have these three options:

  1. Make those private functions methods (they will no longer be private then) and invoke them as methods like this.func2() so the javascript interpreter sets this for you.
  2. Use .call() or .apply() like func2.call(this) to instruct the interpreter to set this as you desire.
  3. Store the value of this in a local variable before calling func1() with something like var self = this so you can refer to self inside func1() via the closure. This is done quite commonly in javascript (takes advantage of how closures allow access to parent scope variables).

You can't do what you want to unless you do use something like setting it to another variable. So either restructure everything so you dont have to do it, or just use the variable. I'd say it's acceptable to use the variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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