2017-09-22 130 views
0

我創建了一個「人」的構造:如何創建其值根據其他變量而變化的變量?

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值現在將David Johns 我試圖修改的person1.firstName值into George

我預計person1.fullName的值更改爲George Johns但它沒有c上吊!

那麼如何製作一個屬性取決於其他屬性的對象呢? 或其值取決於其他變量的變量?

+0

您使用的屬性設置最終的答案我們。 *我可以嗎?不,沒有真正的理由來優化/記憶像這樣的計算屬性。 –

回答

2

您應該使用它使用變量的所有更新值一樣

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

 
let p = new Person('Hello', 'World'); 
 

 
console.log(p.getFullName()); 
 

 
p.firstName = 'Hi'; 
 

 
console.log(p.getFullName());

0

這是因爲它被分配給你應該嘗試的是使得getter返回當前的方法。

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

OOP中一個getter這種情況下,你可以使用一個單獨的方法不是屬性。將所有依賴的屬性視爲方法。 對於你的問題就會像,

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