2017-03-09 4 views
0

js에서 개체를 만들었습니다. 객체의 프로토 타입에 새 속성을 추가하려고합니다. 속성이 인스턴스마다 다를 수 있습니다. 값을 더하기 위해 을 얻으려면을 얻으십시오. 그러나 그것은 나에게 오류를 준다. 아래 코드를 추가했습니다.js에서 객체의 새 속성에 값을 추가 할 수 있습니까?

어떻게하면이 작업을 수행 할 수 있습니까?

나는 이것을 봤다. 그리고 제가 배운 모든 것은 에 의해을 얻습니다. 그들은 기존 속성에 가치를 추가합니다. 그러나 새 속성에 값을 추가하려고합니다. 인스턴스마다 인스턴스가 달라집니다.

var computer = function (name, ram) { 
 
    this.name = name; 
 
    this.ram = ram; 
 
}; 
 

 
Object.defineProperty(computer.prototype, "graphic", { 
 
    set: function graphic(value) { 
 
     this.graphic = value; 
 
    }, 
 
    get: function graphic() { 
 
     return this.graphic; 
 
    }, 
 
}); 
 

 
var vio = new computer("sony", "8gb"); 
 

 

 
vio.graphic = "gtx980"; 
 

 
console.log(vio.graphic);

오류 마사지 :

enter image description here

+0

'오류가 발생합니다. '오류가 무엇인지 추측해야합니까? –

+0

getter/setter 속성을 자체 이름으로 설정할 수 없습니다. 프로토 타입 메소드를 짜증나게하는 local vars를 사용하거나, this.raphic' this.graphic front'this.graphic'을 가져 오거나 설정하십시오. 대신에 : – dandavis

+0

오류 :'Out of stack space'. 파이어 폭스에서 –

답변

1

는 질문을 다시 읽기, 나는 실제 우려 답변 해 드리겠습니다 : 당신이 프로토 타입에 물건을 넣을 때

을, 모든 인스턴스간에 공유됩니다 (클래식 클래스의 클래스에 추가 한 것처럼). 자바와 같은 언어). this에 물건을 넣으면 특정 인스턴스에만 액세스 할 수 있습니다. 세터 또는 게터없이

다음 작품

:

function Computer(name, ram) { // Please use Capital names for constructors 
    this.name = name; 
    this.ram = ram; 
}; 

let vio = new Computer('sony', '8gb'); 
vio.graphic = 'gtx980'; 

graphic 재산은 vio에서 개최 된 예를 들면 존재하는 것 밖에없는 모든 컴퓨터 인스턴스입니다. 다른 한편으로는이 작업을 수행하는, 경우

:

function Computer(name, ram) { 
    this.name = name; 
    this.ram = ram; 
} 

Computer.prototype.graphic = 'gtx980'; 

// All instances of Computer will now have a .graphic with the value of 'gtx980'. 
오류를 얻고있는 이유는 당신이, 당신은 노력하고 graphic에 대한 세터를 정의하는 것입니다

graphic에 할당하려고하는 graphic에 대한 설정자를 호출하는 graphic에 할당하면 .... 그 점을 얻습니다.

해결 방법은 실제 변수의 이름을 변경하는 것입니다 (예 : _graphic).

var computer = function (name, ram) { 
 
    this.name = name; 
 
    this.ram = ram; 
 
}; 
 

 
Object.defineProperty(computer.prototype, "graphic", { 
 
    set: function graphic(value) { 
 
     this._graphic = value; 
 
    }, 
 
    get: function graphic() { 
 
     return this._graphic; 
 
    }, 
 
}); 
 

 
var vio = new computer("sony", "8gb"); 
 

 

 
vio.graphic = "gtx980"; 
 

 
console.log(vio.graphic);
JS하지 않는 것을

주 정말 private 변수가 있습니다. 누군가가 _graphic을 변경하는 것을 막을 수 없습니다.

+0

그것은 작동합니다. 감사. – zoha131

+0

그것의 이론을 알 수 있습니까? 내가 console.log (Object.getOwnPropertyNames (vio));를 호출하면, 그래픽 대신 속성 대신 그래픽이 표시됩니다. 그게 왜? – zoha131

+0

이것이 실제 속성입니다. getter와 setter는 객체의 실제 속성이 아니지만 기본 '_graphic'은입니다. –