函数不执行/不返回值

Javascript Function not executing/returning value

本文关键字:返回值 执行 函数      更新时间:2023-09-26

我有一个函数,我想看看index的值是多少。结果是0。我认为这很奇怪,所以我放了一个console.log in function(),看看它是否正在执行,我没有收到一个输出,告诉我函数()没有被调用。我不知道我做错了什么。

function jsTest() {
    var index = 0;
    var counter = 0;
    var obj = {};
    obj.index = index; //obj.index = 0 at this point
    var func = function () {
        for (index = 0; index < 10; index++) {
            counter += 2;
            console.log(counter); //Doesn't execute for some reason
        }
        obj.index++;
    };
    obj.func = func; //executes function()
    this.index++;
    return index;
}
var x = jsTest();
console.log(x);
obj.func = func;

实际上并没有调用func,它将obj的属性func赋值为函数func。如果要调用func,应该在后面添加括号,如

obj.func = func();