开发者

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. 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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜