简体   繁体   中英

Javascript access object property in method

how do I get this reference right, it returns "foo undefined";

function myObject(){
    this.foo="bar"

    this.foo2=this.myMethod.foo3;

    alert(this.foo2);
}

myObject.prototype.myMethod= {
    foo3:'foo'+this.foo;
}

When you do this...

myObject.prototype.myMethod=
{
foo3:'foo'+this.foo;
}

the value of this is being evaluated from the current context where the object is being created, which likely doesn't have a foo property.


Not sure why you're calling it myMethod , but assigning an Object, but if you actually made it a method, you could then get the correct foo value.

function myObject(){
    this.foo="bar"
    this.foo2=this.myMethod();
    alert(this.foo2);
}
myObject.prototype.myMethod= function() {
    return 'foo'+this.foo;
};

var o = new myObject(); // alerts "foobar", and returns the new object

'foo' + this.foo is immediately concatenated when it's parsed, so it's pretty useless ( this does not refer to an instance).

To get an object which contains variables at the time you want to fetch it, you have to use functions. The function will only execute when you call it, so this.foo refers to the correct value.

function myObject(){
    this.foo="bar";
    this.foo2=this.myMethod().foo3;
    alert(this.foo2);
}

myObject.prototype.myMethod = function() {
    return {
        foo3: 'foo'+this.foo
    };
};

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