Reputation: 8651
Umm i didnt knew a better title,
I wonder if there is a way to do sth. like this:
function myFunc() {
//do some Stuff...
this.myMethod = function(x) {
//do some more Stuff
var nameofthevariable = myVar//somehow get the Variables name
myVar.somePropertie = "SomeOtherStuff";
}
}
myVar = new myFunc();
myVar.myMethod(x)
Thanks for any answers
Thanks for the Answer =), ah thats sad
The Problem with this
is that I have an Object,
a Propertie of the Object creates an Instance of myFunc
and executes myMethod()
this should add a new Propertie to myObj
, so i have the Output from myMethod
seperated from the instance of myFunc()
function myFunc() {
//do some Stuff...
this.myMethod = function(x) {
//do some more Stuff
var nameofthevariable = myObj//somehow get the Variables name
myObj.somePropertie = "SomeOtherStuff";
//and here i could do
this.Parent.somePropertie = "SomeOtherStuff";
}
}
myObj = {}
myObj.myProp = new myFunc();
//i could do:
myObj.myProp.Parent = myObj
//
myObj.myProp.myMethod(x)
But then i could pass myObj
, as an Parameter to the myMethod
too
I wanted to go Up to the Object i want to add sth, twice with the getting of the Variable Name,
I think, this
won't work in that context, as i cant access variables of an level higher than the instance of myFunction
Oh yes, thanks =) in the real Code its a 'privileged' function and i can call the method,
I'll edit it in the Question,
Thanks for pointing that out, i didnt even realize that when writing this in the question here.
It works well except that i dont find a way, dynamically putting back the Data to the Object which holds the Instance"
Upvotes: 1
Views: 96
Reputation: 150080
You can't get the name of the variable, but you seem to be asking how myMethod()
can add a property to myVar
where myVar
is the instance of myFunc
that myMethod()
was called on - in which case using this
will work:
function myFunc() {
//do some Stuff...
this.myMethod = function(x) {
//do some more Stuff
this.somePropertie = "SomeOtherStuff";
}
}
myVar = new myFunc();
myVar.myMethod(x)
Note that the way you had defined myMethod()
it was a private function accessible only from within myFunc()
- to call it with the myVar.myMethod()
syntax you need to make it a property (so I've changed that bit too).
The value of this
within a function depends how the function was called. When you call myFunc()
with the new
operator JS sets this
to the newly created instance. When you call a method with the myVar.myMethod()
"dot" syntax JS sets this
to myVar
.
For more information about this
I'd suggest reading the MDN this
article.
Upvotes: 2