简体   繁体   中英

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM