2017-12-22 6 views
0

firstName 및 lastName 메서드의 현재 값을 표시하는 방법을 잘못 이해합니다. 왜냐하면 지금은 존에 오류가 있습니다. 이름과 존."undefined"in Object.defineProperty in Constructor

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 = ...이며, 이미 Object.defineProperty(this, ...)를 사용하여 정의 된 속성을 오버라이드 (override) this.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

두 번째 솔루션은 필자가 필요로하는 것입니다. 이제 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

예, 감사 여기

추가 개인 특성 this._firstNamethis._lastName를 사용하는 고정 된 버전입니다 . 그러나이 경우 나는 Object.defineProperty 서술자에 의해서만 생성자에 propeties를 설정해야합니다. : –

+0

뭔가 빠진 게 아니라면, defineProperty를 사용하여 쓰기 가능하거나 구성 가능한 것과 같은 표준 메타 데이터를 변경하는 것만으로도 의미가 있습니다. 또는 getter 및 setter가 속성을 반환하는 것 이상을 수행하지 않으면 귀하의 코드에 표시됩니다 .Dmitris 두 번째 솔루션에 가면 cdoshis 코드는 기능상 동일합니다. – 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()); 
관련 문제