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:
object.method()
, then this
is set to the object inside the method. fn()
, this
is set to the global object (which is usually window
in a browser). .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:
this.func2()
so the javascript interpreter sets this
for you. .call()
or .apply()
like func2.call(this)
to instruct the interpreter to set this
as you desire. 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.