从同一类中的其他属性计算的Javascript类的属性

Duc*_*ard 15 javascript properties class

这可能是我很遗憾的东西,但是如何根据同一类中其他属性的值自动重新计算类的属性?

例如

function Test() {
    this.prop1 = 1;
    this.prop2 = 2;
    this.prop3 = this.prop1 + this.prop2;

}

tester = new Test();

alert (tester.prop1); // expect 1
alert (tester.prop2); // expect 2
alert (tester.prop3); // expect 3

tester.prop1 += 1;

alert (tester.prop1); // expect 2
alert (tester.prop2); // expect 2
alert (tester.prop3); // expect 4
Run Code Online (Sandbox Code Playgroud)

或者我是否需要将prop3设置为= calcProp3(),然后包含如下函数:

this.calcProp3 = function() {
        var calc = this.prop1 + this.prop2;
        return calc;
    }
Run Code Online (Sandbox Code Playgroud)

谢谢大家.

T.J*_*der 23

或者我需要将prop3设置为= calcProp3()然后包含一个函数

你有两个选择:

  1. 使用getter创建一个属性,当你使用它时看起来像一个简单的属性访问,但实际上是调用一个函数,或者

  2. 做你的calcProp3功能,这使编码人员Test明白他们正在调用一个函数

如果您需要支持IE8等真正过时的浏览器,则选项2是您唯一的选择,因为IE8不支持getter.

使用吸气剂

在2017年你可能会在一个class(如果有必要的话,不支持ES2015 [又名"ES6"]的浏览器中进行定义class):

class Test {
  constructor() {
    this.prop1 = 1;
    this.prop2 = 2;
  }
  get prop3() {
    return this.prop1 + this.prop2;
  }
}
const t = new Test();
console.log(t.prop3); // 3
t.prop1 = 2;
console.log(t.prop3); // 4
Run Code Online (Sandbox Code Playgroud)

如果你想限制自己的ES5功能(2009年12月发布的规范,IE8不支持),你Test.prototype可以使用Object.defineProperty(spec,MDN)定义一个getter :

function Test() {
  this.prop1 = 1;
  this.prop2 = 2;
}
Object.defineProperty(Test.prototype, "prop3", {
  get: function() {
    return this.prop1 + this.prop2;
  }
});
var t = new Test();
console.log(t.prop3); // 3
t.prop1 = 2;
console.log(t.prop3); // 4
Run Code Online (Sandbox Code Playgroud)

...或者通过替换Test.prototype和使用getter的对象初始化器语法(记得设置constructor):

function Test() {
  this.prop1 = 1;
  this.prop2 = 2;
}
Test.prototype = {
  constructor: Test,
  get prop3() {
    return this.prop1 + this.prop2;
  }
};
var t = new Test();
console.log(t.prop3); // 3
t.prop1 = 2;
console.log(t.prop3); // 4
Run Code Online (Sandbox Code Playgroud)

使用功能

在2017年,您可能将其定义为使用class语法的方法(如果旧浏览器需要,则进行转换):

class Test {
  constructor() {
    this.prop1 = 1;
    this.prop2 = 2;
  }
  calcProp3() {
    return this.prop1 + this.prop2;
  }
}
const t = new Test();
console.log(t.calcProp3()); // 3
t.prop1 = 2;
console.log(t.calcProp3()); // 4
Run Code Online (Sandbox Code Playgroud)

如果你想坚持ES5(实际上在这种情况下是ES3)功能来支持过时的浏览器,只需在原型中添加一个函数:

function Test() {
  this.prop1 = 1;
  this.prop2 = 2;
}
Test.prototype.calcProp3 = function calcProp3() {
  return this.prop1 + this.prop2;
};
var t = new Test();
console.log(t.calcProp3()); // 3
t.prop1 = 2;
console.log(t.calcProp3()); // 4
Run Code Online (Sandbox Code Playgroud)