[英]Javascript context issue using Object.create() and function.apply doesn't seem to work?
I am running into the error with object context when trying to use Object.create.在尝试使用 Object.create 时,我遇到了 object 上下文的错误。 This is a very simple example, but this is what I am doing:这是一个非常简单的例子,但这就是我正在做的:
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.表达式 'this.memberVariable' [undefined] 的结果不是 object。
To remember this problem, I thought that I could use apply to give the correct context to the function.为了记住这个问题,我认为我可以使用 apply 为 function 提供正确的上下文。 So I replaced object1 with something like:所以我用类似的东西替换了object1:
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.现在我收到一条错误消息,说表达式“functionArg.apply”[undefined] 的结果不是 function。 I assume that's because object2 is using value notation.我认为这是因为 object2 使用了值表示法。 I tried changing it to functionArg.value.apply but got the same result.我尝试将其更改为 functionArg.value.apply 但得到了相同的结果。 Should this work?这应该工作吗?
Either functionArg
is a string, in which case you have to use bracket notation:任一functionArg
都是字符串,在这种情况下,您必须使用括号表示法:
func1: function(functionArg){
...
this[functionArg]();
}
or it is a function reference, which case it should be或者它是 function 参考,在这种情况下应该是
functionArg.apply(this)
It depends on what func3
is in this line: this.func1(func3)
.这取决于这一行中的func3
是什么: this.func1(func3)
。 As it stands, func3
is not defined.就目前而言, func3
没有定义。
In any case, this.functionArg
is wrong, you have no property functionArg
defined anywhere.无论如何, this.functionArg
是错误的,您在任何地方都没有定义属性functionArg
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.