2017-12-22 24 views
0

firstNameメソッドとlastNameメソッドの現在の値を表示する方法が間違っていることは理解できません。今のところ私はjone.Nameとjone.lastにエラーがあります。なぜなら、それらは不定になるからです。コンストラクタのObject.definePropertyの取得で「未定義」

function User(fullName) { 
    this.fullName = fullName.split(' '); 

    Object.defineProperty(this, 'firstName', { 
    get: function() { 
     this.firstName = this.fullName[0]; 
     return this.firstName; 
    } 
    }); 

    Object.defineProperty(this, 'lastName', { 
    get: function() { 
     this.lastName = this.fullName[1]; 
     return this.lastName; 
    } 
    }); 

} 

var jone= new User("Jone Coven"); 

console.log(jone.fullName); 
console.log(jone.firstName); 
console.log(jone.lastName); 

答えて

3

問題がthis.firstName = ...this.lastName = ...既にObject.defineProperty(this, ...)を使用して定義されたプロパティを上書きすることです。

ここでは、追加のプライベートプロパティthis._firstNamethis._lastNameを使用して固定されたバージョンです:

function User(fullName) { 
    this.fullName = fullName.split(' '); 

    Object.defineProperty(this, 'firstName', { 
    get: function() { 
     this._firstName = this.fullName[0]; // <------ _firstName 
     return this._firstName; 
    } 
    }); 

    Object.defineProperty(this, 'lastName', { 
    get: function() { 
     this._lastName = this.fullName[1]; // <----- _lastName 
     return this._lastName; 
    } 
    }); 

} 

var jone= new User("Jone Coven"); 

console.log(jone.fullName); 
console.log(jone.firstName); 
console.log(jone.lastName); 

は別の解決策は、すぐに結果を返すことです:

function User(fullName) { 
    this.fullName = fullName.split(' '); 

    Object.defineProperty(this, 'firstName', { 
    get: function() { 
     return this.fullName[0]; 
    } 
    }); 

    Object.defineProperty(this, 'lastName', { 
    get: function() { 
     return this.fullName[1]; 
    } 
    }); 

} 

var jone= new User("Jone Coven"); 

console.log(jone.fullName); 
console.log(jone.firstName); 
console.log(jone.lastName); 

+0

2番目の解決策は私が必要とするものですが、今私はdefinePropertyで間違っていることを理解しています。 –

2

これはなぜ複雑ですか?

function User(fullName) { 
    this.fullName = fullName.split(' '); 
    this.firstName = this.fullName[0]; 
    this.lastName = this.fullName[1]; 
} 

var jone= new User("Jone Coven"); 
+0

はい、ありがとうございます。しかし、この場合は、Object.defineProperty記述子だけでプロティテイをコンストラクタに設定する必要があります。 :( –

+0

私は何かが欠けていない限り、definePropertyを使って書き込み可能、​​設定可能などの標準メタデータの一部を変更すると意味があります。あるいは、getterとsetterが単にプロパティを返すだけではなく、 – Shilly

0
function User(fullName) { 
    this.fullName = fullName.split(' '); 
this.firstName = function() { 
     return this.fullName[0]; 

    } 
this.lastName = function() { 
     return this.fullName[1]; 

    } 
} 

var jone= new User("Jone Coven"); 

console.log(jone.fullName); 
console.log(jone.firstName()); 
console.log(jone.lastName()); 
関連する問題