如何将一个方法的返回值赋给Javascript中的另一个对象属性?

How do I assign the return value from a method to another object property in Javascript?

本文关键字:Javascript 属性 一个对象 返回值 方法 一个      更新时间:2023-09-26

我正在将一些旧代码转换为Javascript中的对象文字表法,恐怕我遇到了一点麻烦。我知道如何定义属性,也知道如何定义方法,但如果我想将方法的返回值赋值为属性,该怎么办?

我已经从Chrome的控制台提供了错误输出的代码。我不知道我做错了什么,但控制台告诉我,我要么试图去全局作用域中不存在的东西,要么就是不存在的东西。

代码:

var testobj = {
    a: 2,
    b: 4,
    c: function() {
        return this.a * this.b;
    },
    d: this.c(), // OK, got it, it's trying to call it from global scope. Fine.
    e: function() {
        if (this.d) {
            console.log("SUCCESS");
            console.log(this.d);
        } else {
            console.log("ERROR");
        }
    }
}
错误:

TypeError: Object [object global] has no method 'c'
新代码:

var testobj = {
    a: 2,
    b: 4,
    c: function() {
        return this.a * this.b;
    },
    d: testobj.c(), // but if I change it like this, it still doesn't work. What gives?
    e: function() {
        if (this.d) {
            console.log("SUCCESS");
            console.log(this.d);
        } else {
            console.log("ERROR");
        }
    }
}
新错误:

TypeError: Cannot call method 'c' of undefined

有人能看出我做错了什么吗?

你可以使用:

var testobj = {
    a: 2,
    b: 4,
    c: function() {
        return this.a * this.b;
    },
    d: function() {
        return this.c();
    },
    e: function() {
        if (this.d) {
            console.log("SUCCESS");
            console.log(this.d);
        } else {
            console.log("ERROR");
        }
    }
}

当您执行d: this.c()时,this实际上是全局对象。这是因为,在创建testobj时,作用域是全局对象,所以this是全局对象。

如果使用

d: function() {
    return this.c();
}

你只是将testobj.c设置为某个功能。该函数中的this只在调用d时计算。因此,当您调用d时,它将检查作用域,并看到作用域是testobj。由于testobj有一个c函数,它将调用并返回该函数。

我把它放在一个jsFiddle来看看它的作用

可以了((http://jsfiddle.net/balintbako/n6YjE/):

)
var testobj = {
    a: 2,
    b: 4,
    c: function () {
        alert(this.a + this.b);
    },
    d: function () {
        this.c();
    }
};
testobj.c();

我相信你想看到d中c的返回值。

在这种情况下,我在对象之后赋值d,因为它在var ob = {...}中没有任何实例,因为它仍在创建中。

var testobj = {
    a: 2,
    b: 4,
    c: function() {
        return this.a * this.b;
    },
    e: function() {
        if (this.d) {
            console.log("SUCCESS");
            console.log(this.d);
        } else {
            console.log("ERROR");
        }
    }
}
testobj.d = testobj.c();
alert(testobj.d);
alert(testobj.c());