2012-03-02 2 views
0
var Person = function(){}; 


function klass() { 
    initialize = function(name) { 
      // Protected variables 
      var _myProtectedMember = 'just a test'; 

      this.getProtectedMember = function() { 
      return _myProtectedMember; 
      } 

      this.name = name; 
       return this; 
     }; 
    say = function (message) {     
      return this.name + ': ' + message + this.getProtectedMember(); 
      // how to use "return this" in here,in order to mark the code no error. 
     }; 
//console.log(this); 

return { 
       constructor:klass, 
     initialize : initialize, 
     say: say 
    } 
    //return this; 
} 

Person.prototype = new klass(); 
//console.log(Person.prototype); 
new Person().initialize("I :").say("you ").say(" & he"); 

"say"에 "return this"를 사용하는 방법으로 코드에 오류가 없음을 표시합니다.자바 스크립트 "return this"가 "return"을 충족합니까?

나는 alrealy를 반환하는 함수에서 'Chain call'하는 방법을 알고 싶습니까?

+2

함수처럼 호출 - this

say = function (message) { // show the message here e.g. using an alert alert(this.name + ': ' + message + this.getProtectedMember()); // then return instance return this; }; 

두 함수 내에서 메시지를 표시 ANS 반환 연쇄를 허용하기 위해 응답 메시지 또는 객체 자체를 반환 할 수 있습니다. 동시에 둘 다 반환 할 수는 없습니다. – Simon

답변

0

호출을 연결하려면 클래스 인스턴스를 반환해야합니다. 클래스의 출력을 저장할 수있는 모든 객체에 대한 기본 클래스를 생성하고 "toString"또는 유사한 함수 (아마도 "출력")로 반환 할 것을 제안합니다.

코드는 다음이된다 :

(new Person()).initialize("I :").say("you ").say(" & he").toString(); 
0

하나의 개체를 반환 할 수 있습니다.

두 가지 옵션이 있습니다.

하나는 - 인스턴스 메시지

say = function (message) { 
    message = this.name + ': ' + message + this.getProtectedMember();    
    return {message:message, instance:this}; 
}; 

를 포함하는 객체를 반환하고

new Person().initialize("I :").say("you ").instance.say(" & he"); 
관련 문제