Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使变量的值随其他变量的变化而变化?_Javascript_Oop - Fatal编程技术网

Javascript 如何使变量的值随其他变量的变化而变化?

Javascript 如何使变量的值随其他变量的变化而变化?,javascript,oop,Javascript,Oop,我创建了一个“Person”构造函数: function Person(firstName, secondName) { 'use strict'; this.firstName = firstName; this.secondName = secondName; this.fullName = this.firstName + ' ' + this.secondName; } ,然后我创建了它的一个实例: var person1 = new Person('David', '

我创建了一个“Person”构造函数:

function Person(firstName, secondName) {
  'use strict';
  this.firstName = firstName;
  this.secondName = secondName;
  this.fullName = this.firstName + ' ' + this.secondName;
}
,然后我创建了它的一个实例:

var person1 = new Person('David', 'Johns');
person1.fullName
的值现在将是
davidjohns
我试图将
person1.firstName
的值修改为
George

我希望
person1.fullName
的值变为
George Johns
,但它没有变

那么,如何创建一个属性依赖于其他属性的对象呢?
或者其值依赖于其他变量的变量?

这是因为它被分配了一个getter,您应该尝试使用如下方法创建一个getter,返回当前的getter

function getFullName() {
    return this.firstName + ' ' + this.secondName;
}

这是因为它被分配了一个getter,您应该尝试的是创建一个getter,该getter使用如下方法返回当前getter

function getFullName() {
    return this.firstName + ' ' + this.secondName;
}

您应该使用一个getter,它使用变量的所有更新值,如

职能人员(第一名,第二名){
"严格使用",;
this.firstName=firstName;
this.secondName=secondName;
this.getFullName=()=>this.firstName+“”+this.secondName;
}
设p=新人(“你好”,“世界”);
log(p.getFullName());
p、 firstName='Hi';

log(p.getFullName())您应该使用一个getter,它使用变量的所有更新值,如

职能人员(第一名,第二名){
"严格使用",;
this.firstName=firstName;
this.secondName=secondName;
this.getFullName=()=>this.firstName+“”+this.secondName;
}
设p=新人(“你好”,“世界”);
log(p.getFullName());
p、 firstName='Hi';

log(p.getFullName())在oop中,对于此类实例,您可以使用单独的方法而不是属性。将所有依赖的属性都视为方法。 你的问题是

function Person(firstName, secondName) {
  'use strict';
  this.firstName = firstName;
  this.secondName = secondName;
  this.getFullName = function(){return this.firstName + ' ' + this.secondName};
} 

在oop中,对于这样的实例,可以使用一个单独的方法而不是属性。将所有依赖的属性都视为方法。 你的问题是

function Person(firstName, secondName) {
  'use strict';
  this.firstName = firstName;
  this.secondName = secondName;
  this.getFullName = function(){return this.firstName + ' ' + this.secondName};
} 

最终的答案是使用属性设置器。我会吗?不,没有真正的理由优化/记忆这样的计算属性。最终的答案是使用属性设置器。我会吗?不,没有真正的理由优化/记忆这样的计算属性。