Javascript 如何使变量的值随其他变量的变化而变化?
我创建了一个“Person”构造函数: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', '
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};
}
最终的答案是使用属性设置器。我会吗?不,没有真正的理由优化/记忆这样的计算属性。最终的答案是使用属性设置器。我会吗?不,没有真正的理由优化/记忆这样的计算属性。