2014-01-16 5 views
0

이미 정의 된 모델에 새 메서드를 추가 할 수있는 방법이 있습니까? 이미 정의 된 모델에 녹아웃 추가 메서드

var MyModel = function() { 

    var self = this; 
    self.method1 = function() { 
    return true; 
    } 
    self.method2 = function() { 
    return true; 
    } 
}; 


viewModel = new MyModel(); 
ko.applyBindings(viewModel); 

나에게 viewModel.method1()viewModel.method2()에 액세스 할 수 있습니다하지만 난 같은 방식으로, 예를 들어에 액세스 할 수있는 파일에 나중에 새로운 방법을 추가 할 수 있도록

viewModel.extend = function() { 
    self.method3 = function() { 
    return true; 
    } 
} 

그리고 지금은 viewModel.method1(), viewModel.method2()viewModel.method3()

어떤 아이디어가 액세스 할 수있는 것? 당신은 프로토 타입을 사용하여 하나 정의 할 수 있습니다

감사

답변

1

: 당신의 예에서

MyModel.prototype.method3 = function() { 
    var self = this; // Reference to instance of MyModel 
    var m1 = self.method1(); 
    var m2 = self.method2(); 
    return true; 
}; 

:

var MyModel = function() { 

    var self = this; 
    self.method1 = function() { 
    return true; 
    } 
    self.method2 = function() { 
    return true; 
    } 
}; 


viewModel = new MyModel(); 
ko.applyBindings(viewModel); 

MyModel.prototype.method3 = function() { 
    return true; 
}; 

console.log(viewModel.method3()); 
+0

가 완벽하게, 내가 필요 얼마나 작동합니다. 고맙습니다 –

관련 문제