개체 자체에서 함수 및 멤버를 선언하는 대신 .prototype을 사용하는 기술적 인 이유는 무엇입니까? 코드 예제로 설명하는 것이 가장 쉽습니다.Javascript에서 .prototype을 사용하는 이유
는 사용의 장점은 무엇 같습니다
RobsObject = function(data){
this.instanceID = data.instanceID;
this._formButton = document.getElementById('formSubmit_' + this.instanceID);
if(this._formButton)
{
//set a click listener that
//points to this._onSubmit, this._onSuccess, and this.onFailure
}
this._onSubmit = function(type, args)
{
//make an ajax call
}
this._onSuccess = function(type, args)
{
//display data on the page
}
this._onFailure = function(type, args)
{
//show an alert of some kind
}
};
감사 :
는RobsObject = function(data){
this.instanceID = data.instanceID;
this._formButton = document.getElementById('formSubmit_' + this.instanceID);
if(this._formButton)
{
//set a click listener that
//points to this._onSubmit, this._onSuccess, and this.onFailure
}
};
RobsObject.prototype = {
_onSubmit: function(type, args)
{
//make an ajax call
},
_onSuccess: function(type, args)
{
//display data on the page
},
_onFailure: function(type, args)
{
//show an alert of some kind
},
};
으로 같은 개체의 내부에 함수를 선언에 반대한다.
편집 : 많은 사람들이 두 번째 코드 스 니펫에있는 내 기능이 공개되기 위해 앞에 'this'가 있어야한다고 지적했습니다. 그래서 나는 그것을 추가했다. 내 실수.
두 번째 코드 스 니펫에서'this._onSubmit = ...','this._onSuccess = ... '등을 사용하셨습니까? 그렇지 않은 경우, RobsObject 생성자로 인스턴스화 된 객체의 속성이 아닙니다. –