Javascript context issue using Object.create() and function.apply doesn't seem to work?
var object1 = {
func1: function(functionArg){
...
functionArg();
}
}
var object2 = {
func2: {
value: function(){
this.memberVariable = 1;
...
this.func1(this.func3)
}
}
func3: {
value: function(){
if(this.memberVariable == 1){};
...
}
}
}
var newObject = Object.create(object1,object2);
newObject.func2();
The Result of expression 'this.memberVariable' [undefined] is not an object.
To remember this problem, I thought that I could use apply to give the correct context to the function. So I replaced object1 with something like:
var object1 = {
func1: function(functionArg){
var thisObject = this;
var functionArgApply = function(){
functionArg.apply(thisObject,arguments);
};
...
functionArgApply();
}
}
Now I get an error saying Result of expression 'functionArg.apply' [undefined] is not a function. I assume that's because object2 is using value notation. I tried changing it to functionArg.va开发者_运维知识库lue.apply but got the same result. Should this work?
Either functionArg
is a string, in which case you have to use bracket notation:
func1: function(functionArg){
...
this[functionArg]();
}
or it is a function reference, which case it should be
functionArg.apply(this)
It depends on what func3
is in this line: this.func1(func3)
. As it stands, func3
is not defined.
In any case, this.functionArg
is wrong, you have no property functionArg
defined anywhere.
精彩评论