简体   繁体   English

方法中的Javascript访问对象属性

[英]Javascript access object property in method

how do I get this reference right, it returns "foo undefined"; 我该如何正确获取此引用,它返回“ 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. 的值this正在从其中被创建对象的当前上下文,这可能不具有评价foo属性。


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. 不知道为什么要调用它myMethod ,而是分配一个Object,但是如果您实际上使它成为一个方法,则可以获取正确的foo值。

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). 'foo' + this.foo在解析时会立即连接在一起,因此它几乎没有用( this不涉及实例)。

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. 该函数仅在调用时执行,因此this.foo引用正确的值。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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