1

https://jsfiddle.net/ca4xvkzb/

    function foo(a,b)
    {
        this.a = a
      this.b = b
      this.bar = a+b
    }
    var z = new foo();
    z.a = 2
    z.b = 3
    console.log(z.bar)

目前发生了什么:

z.bar返回 NaN,进一步的测试暗示在更新它们的值时,z.aof正在使用 a 和 b 的旧未定义值,而不是更新后的值z.bthis.barz

我需要发生的事情:

z.bar应该正确返回值a+b:5,在对象定义之后设置它们之后,因为我想将foo对象用于更多变量而不仅仅是z

4

2 回答 2

0

你可以这样使用它:

function foo(a,b)
{
  this.a = a
  this.b = b
  this.bar = ()=> this.a + this.b
}
var z = new foo();
z.a = 2
z.b = 3
console.log(z.bar())
于 2021-08-24T10:21:35.310 回答
0

正如 walidum 所评论的,您正在创建bar作为实例ownProperty的函数。foo我认为将 bar 作为 foo 类 per 的函数包含在内会更有意义prototype

function foo(a,b) {
  this.a = a;
  this.b = b;
}
foo.prototype.bar = function(){ return this.a + this.b; };


var z = new foo();
z.a = 2
z.b = 3
console.log(z.bar()); // = 5
console.log(z.hasOwnProperty('a')); // = true -- because it's something that belongs to THIS very instance of foo
console.log(z.hasOwnProperty('bar')); // = false -- because the function does not belong to the instance, but to the class (all instances of) foo.
于 2021-08-24T10:58:14.737 回答