方法调用模式不工作

Method invocation pattern not working?

本文关键字:工作 模式 调用 方法      更新时间:2023-09-26

我只是在学习JavaScript,它有一个叫做方法:

像这样的一个例子,我希望它能工作,但我在FireFox中写它,它什么也没做:

var myObject = {
 value: 0,
 increment: function (inc) {
   this.value += inc;
   }
};
console.writeln(myObject.value);
var x = myObject.increment(2);
console.writeln(x);

怎么了?

1)用console.log代替console.writeln

2)你必须从函数返回。如果没有,获取值的唯一方法是请求值

var myObject = {
    value: 0,
    increment: function (inc) {
        return this.value += inc;
    }
};

必须返回一个值:

var myObject = {
    value: 0,
    increment: function (inc) {
        this.value += inc;
        return this.value;
    }
};

你想要console.log而不是console.writeln

下面是一个工作示例:http://jsfiddle.net/AS9BH/